NG-类Angular2 [英] ng-class in Angular2
问题描述
我发展的角度2测试应用程序,我坚持使用基于模型从列表中添加类的问题。
I am developing a test application in angular 2 and I'm stuck with a problem of adding classes based on list from model.
在角1人可以做的:
// model
$scope.myClasses = ['class1', 'class2', ...];
// view
... ng-class="myClasses" ...
在角2,所有我已经能够到目前为止做的是:
In Angular 2, all I have been able to do so far is:
// view
... [class.class1]="true" [class.class2]="true" ...
这显然是非常有活力,我相信一定有更好的方法来做到这一点。
Which is obviously not very dynamic and I'm sure there must be a better way to do this.
不过,我也尝试:
// model
class ... {
private myClasses: any;
constructor() {
this.myClasses = ['class1', 'class2', ...];
}
// view
... [class]="myClasses" ...
但是,这并不工作,我曾尝试 myClasses
作为一个单独的类的字符串名称,字符串数组,对象与类名键和真正作为一种价值,这种对象的数组,但可悲的是,没有上市会以这种方式工作。
but this doesn't work, I have tried myClasses
as a string name of a single class, array of strings, object with a classname key and true as a value, an array of objects of this kind, but sadly, nothing of listed will work this way.
推荐答案
您必须指定<一个href=\"https://github.com/angular/angular/blob/2.0.0-alpha.22/modules/angular2/src/directives/class.js#L12\"><$c$c>CSSClass$c$c>在<一个href=\"https://github.com/angular/angular/blob/2.0.0-alpha.22/modules/angular2/src/core/annotations_impl/view.js#L72\"><$c$c>directives$c$c>财产<一个href=\"https://github.com/angular/angular/blob/2.0.0-alpha.22/modules/angular2/src/core/annotations_impl/view.js#L35\"><$c$c>@View$c$c>装饰。看看这个普拉克。
@Component({
selector: 'app',
})
@View({
template: '<div [class]="classMap">Class Map</div>',
directives: [CSSClass]
})
class App {
constructor() {
this.classMap = { 'class1': true, 'class2': false };
setInterval(() => {
this.classMap.class2 = !this.classMap.class2;
}, 1000)
}
}
UPD
的CssClass
更名以<一个href=\"https://github.com/angular/angular/blob/2.0.0-alpha.40/modules/angular2/src/core/directives/ng_class.ts#L35\"><$c$c>NgClass$c$c>在阿尔法-35。请参见这普拉克
@Component({
selector: 'app',
})
@View({
directives: [NgClass],
template: `
<div [ng-class]="classMap">Class Map</div>
`,
})
class App { /* ... */ }
这篇关于NG-类Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!