Html 角度10 |将类名作为变量添加到ngClass

Html 角度10 |将类名作为变量添加到ngClass,html,css,angular,Html,Css,Angular,我有20多个元素,它们都应该使用相同的类(animate.css) 如果我想编辑动画,更改所有类是非常烦人的,因此我将动画类保存在我的服务中的一个变量中: animClassSecond = "animate__animated animate__bounceInUp"; 但我不知道如何将其添加到[ngClass],这不起作用: [ngClass]="{'select_elem':true, 'btn_2':true, 'dataService.animClass

我有20多个元素,它们都应该使用相同的类(animate.css)

如果我想编辑动画,更改所有类是非常烦人的,因此我将动画类保存在我的服务中的一个变量中:

animClassSecond = "animate__animated animate__bounceInUp";
但我不知道如何将其添加到[ngClass],这不起作用:

[ngClass]="{'select_elem':true, 'btn_2':true, 'dataService.animClassSecond':true}"
[ngClass]="{'select_elem':true, 'btn_2':true, 'this.dataService.animClassSecond':true}"
[ngClass]="{'select_elem':true, 'btn_2':true, this.dataService.animClassSecond:true}"
[ngClass]="{'select_elem':true, 'btn_2':true, dataService.animClassSecond:true}"
它可能是一个模板错误,或者它没有解析为变量。有什么想法吗


注意:添加第二个[ngClass]属性也不起作用,因为第一个属性被忽略。

这在模板中可能无法实现,因为角度模板语言非常有限

只需将ngClass对象的逻辑移到component.ts中即可。在那里,您可以使用所有TypeScript的功能

ngOnInit() {
  this.ngClassObj = { [dataService.animClassSecond]: true };
}
或者,如果您需要它是动态的(请小心使用,因为它可能会成为性能问题)

然后

[ngClass]="ngClassObj"

这在模板中可能无法实现,因为Angular模板语言非常有限

只需将ngClass对象的逻辑移到component.ts中即可。在那里,您可以使用所有TypeScript的功能

ngOnInit() {
  this.ngClassObj = { [dataService.animClassSecond]: true };
}
或者,如果您需要它是动态的(请小心使用,因为它可能会成为性能问题)

然后

[ngClass]="ngClassObj"
是:

但是请记住,您需要在构造函数中声明公共服务

constructor(public dataService:DataService){}
注意:您可以在同一标记中使用class和[ngClass]:

class="select_elem btn_2" [ngClass]="dataService.animClassSecond"
是:

但是请记住,您需要在构造函数中声明公共服务

constructor(public dataService:DataService){}
注意:您可以在同一标记中使用class和[ngClass]:

class="select_elem btn_2" [ngClass]="dataService.animClassSecond"