我是 Angular 的新手,只是一个关于在属性指令中使用 @Attribute 的问题,下面是书中的一些代码:
@Directive({
selector: "[pa-attr]",
})
export class PaAttrDirective {
constructor(element: ElementRef, @Attribute("pa-attr") bgClass: string) {
element.nativeElement.classList.add(bgClass || "bg-success", "text-white");
}
}
和模板.html:
...
<td pa-attr="bg-warning">{{item.category}}</td>
...
所以我们可以看到使用@Attribute我们可以获得属性的值,但是如果我们使用数据绑定属性指令为:
<td [pa-attr]="item.category == 'Soccer' ? 'bg-info' : null">...
然后书修改代码为:
export class PaAttrDirective {
constructor(private element: ElementRef) {}
@Input("pa-attr")
bgClass: string;
ngOnInit() {
this.element.nativeElement.classList.add(this.bgClass || "bg-success", "text-white");
}
}
我在这里有点困惑,我们不能使用 @Attribute 再次获取值:
export class PaAttrDirective {
constructor(element: ElementRef, @Attribute("pa-attr") bgClass: string) {
element.nativeElement.classList.add(bgClass || "bg-success", "text-white");
}
}
为什么当将属性指令与数据绑定一起使用时,我们必须在代码中创建输入属性而不能使用@Attribute?
互换的青春
牛魔王的故事
相关分类