为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

紫衣仙女 2021-12-02 10:36:43
我是 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 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

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

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

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

我建议在这里阅读Angular 模板语法


查看完整回答
反对 回复 2021-12-02
?
牛魔王的故事

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>

我不确定您是否可以在输入属性名称中使用破折号。


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 207 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信