首页 > 解决方案 > 为什么数据绑定不适用于我的自定义属性指令

问题描述

下面是我的代码,我省略了组件代码的缩写:

模板.html

 ...
 <tr *ngFor="let item of getProducts(); let i = index"
     [pa-attr]="getProducts().length < 6 ? 'bg-success' : 'bg-warning'">
     <td>{{item.name}}</td>             
 </tr>

以下是自定义属性指令代码:

@Directive({
    selector: "[pa-attr]",
})
export class PaAttrDirective {

    constructor(private element: ElementRef) {
        console.log('been called')
    }

    @Input("pa-attr")
    bgClass: string;

    ngOnInit() {
        this.element.nativeElement.classList.add(this.bgClass || "bg-success",
            "text-white");
    }
}

目前我有5个项目: 在此处输入图像描述

然后我添加一个新项目,然后我有: 在此处输入图像描述

我在这里很困惑,为什么只有第六个项目的颜色变为黄色(bg-warning)?是否应该将所有项目的颜色都更改为黄色?因为当我添加一个新项目时,数据源发生了getProducts()变化,所以getProducts().length返回了六个项目,由于数据源发生了变化,所以<tr>应该重新评估整体,所以现在每个项目从第 1 到第 6 应该是黄色的,不是吗?那么为什么只有第六项是黄色的呢?

标签: javascriptangular

解决方案


我没有做很多 Angular,但这看起来就像我期望的代码一样。每次通过循环 ( ) 时,由于属性中的逻辑,let item of getProducts()前 5行<tr>(表)将应用该类,除了应用之外的所有内容。bg-success[pa-attr]bg-warning


推荐阅读