在自定义属性指令和数据绑定属性指令中使用@Attribute

问题描述 投票:0回答:2

我是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可以获取属性的值,但是如果我们使用data-binding 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?

javascript angular
2个回答
0
投票

@@ Attribute:接受简单的原始类型,例如字符串和数字@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
投票

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

属性初始化DOM属性,然后完成。属性值可以改变;属性值不能。

[item.category == 'Soccer' ? 'bg-info' : null]表达式会更改属性值,因此您的指令在更改后将无法获取更新的值。

我建议阅读about Angular template syntax here

© www.soinside.com 2019 - 2024. All rights reserved.