如何从类组件动态设置 Angular 中元素的 CSS 类列表?

问题描述 投票:0回答:3

我想将属性设置为字符串,并将其作为类列表值动态添加到某个 DOM 元素中。

<div [className]="propertyVariable"></div>

在类组件内部:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.css'],
})
export class OrderComponent implements OnInit {
  propertyVariable: string;

  constructor() {}

  changePropertyVariable() {
    this.propertyVariable = 'class1 class2';
  }

  ngOnInit(): void {}
}

到目前为止,它还没有将类列表设置添加到该变量。我如何正确绑定到该属性?

javascript html node.js angular ecmascript-6
3个回答
0
投票

为什么不使用带有属性绑定的 Angular ngClass 指令来动态添加类?

<div [ngClass]="propertyVariable"></div>

https://angular.io/guide/property-binding


0
投票

[class.className]="condition"
一样使用它来添加className(如果condition为真)。在这种情况下,className被硬编码在模板中。

如果您希望类名是动态的,您可以使用以下语法:

class="class1 class2 {{className}}"

要附加类列表,您可以像上面一样使用它,只需将

className = classList.join(' ');
传递为
className

所以你的模板将是这样的:

class="class1 class2 itemOneFromList itemTwoFromList ..."

我提供了一个stackblitz


0
投票

来自“@angular/core”的用户渲染器2

类似的东西:

从“@angular/core”导入{Renderer2}; 。 。 .

构造函数( 私有渲染器:Renderer2 ){}

。 。 。 this.renderer.removeClass(your_node, 'hide_node'); this.renderer.addClass(your_node, 'show_node')

© www.soinside.com 2019 - 2024. All rights reserved.