我是 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?
2 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
互换的青春
TA贡献1797条经验 获得超6个赞
他们使用@Input
而不是@Attribute
因为:
属性初始化 DOM 属性,然后它们就完成了。属性值可以改变;属性值不能。
item.category == 'Soccer' ? 'bg-info' : null
表达式更改属性值,因此您的指令在更改后不会获得更新的值。
我建议在这里阅读Angular 模板语法。
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
牛魔王的故事
TA贡献1830条经验 获得超3个赞
接受简单的原始类型,例如字符串和数字 @Input:接受任何东西/一个对象,例如您自己的类对象
您abc
可以像这样将字符串传递给属性:
<td pa-attr="abc"></td>
您将相同的内容传递给输入,如下所示:
<td [pa-attr]="'abc'"></td> <!-- note the single quotes -->
或者在 ts
x = 'abc';
在 html 中
<td [pa-attr]="x"></td>
我不确定您是否可以在输入属性名称中使用破折号。
添加回答
举报
0/150
提交
取消