gpt4 book ai didi

javascript - 在自定义属性指令和数据绑定(bind)属性指令中使用@Attribute

转载 作者:行者123 更新时间:2023-11-30 19:10:31 24 4
gpt4 key购买 nike

我是 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");
}
}

和 template.html:

...
<td pa-attr="bg-warning">{{item.category}}</td>
...

所以我们可以看到使用@Attribute 我们可以获得属性的值,但是如果我们使用数据绑定(bind)属性指令如下:

<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");
}
}

为什么在使用带有数据绑定(bind)的属性指令时,我们必须在代码中创建输入属性而不能使用@Attribute?

最佳答案

他们使用 @Input 而不是 @Attribute 因为:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

item.category == '足球' ? 'bg-info' : null 表达式更改属性值,因此您的指令在更改后不会获得更新的值。

我建议阅读 about Angular template syntax here .

关于javascript - 在自定义属性指令和数据绑定(bind)属性指令中使用@Attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58534115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com