我是 Angular 的新手,只是一個(gè)關(guān)于在屬性指令中使用 @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我們可以獲得屬性的值,但是如果我們使用數(shù)據(jù)綁定屬性指令為:<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"); }}我在這里有點(diǎn)困惑,我們不能使用 @Attribute 再次獲取值:export class PaAttrDirective { constructor(element: ElementRef, @Attribute("pa-attr") bgClass: string) { element.nativeElement.classList.add(bgClass || "bg-success", "text-white"); }}為什么當(dāng)將屬性指令與數(shù)據(jù)綁定一起使用時(shí),我們必須在代碼中創(chuàng)建輸入屬性而不能使用@Attribute?
在自定義屬性指令和數(shù)據(jù)綁定屬性指令中使用 @Attribute
紫衣仙女
2021-12-02 10:36:43