簡體   English   中英

在自定義屬性指令和數據綁定屬性指令中使用 @Attribute

[英]use @Attribute in custom attribute directive and data -binding attribute directive

我是 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?

他們使用@Input而不是@Attribute ,因為:

屬性初始化 DOM 屬性,然后它們就完成了。 屬性值可以改變; 屬性值不能。

item.category == 'Soccer'? 'bg-info': null item.category == 'Soccer'? 'bg-info': null表達式更改屬性值,因此您的指令在更改后不會獲得更新的值。

我建議在這里閱讀 Angular 模板語法

@Attribute:接受簡單的原始類型,例如字符串和數字 @Input:接受任何東西/一個 object,例如您自己的 class object

您將字符串abc傳遞給屬性,如下所示:

<td pa-attr="abc"></td>

您將相同的內容傳遞給輸入,如下所示:

<td [pa-attr]="'abc'"></td> <!-- note the single quotes -->

或者在 ts

x = 'abc';

在 html

<td [pa-attr]="x"></td> 

我不確定您是否可以在輸入屬性名稱中使用破折號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM