javascript - 为什么数据绑定(bind)不适用于我的自定义属性指令

标签 javascript angular

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

template.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 个项目: enter image description here

然后我添加一个新项目,然后我有: enter image description here

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

最佳答案

"since the data source changes, the whole <tr> should be reevaluated" - 这种说法是不正确的。

*ngFor引擎盖下有许多优化。在这种情况下,前 5 <tr>实例保持不变,仅添加一个新实例。

When the contents of the iterator changes, NgForOf makes the corresponding changes to the DOM:

  • When an item is added, a new instance of the template is added to the DOM.
  • When an item is removed, its template instance is removed from the DOM.
  • When items are reordered, their respective templates are reordered in the DOM.

Angular uses object identity to track insertions and deletions within the iterator and reproduce those changes in the DOM.

如果您在添加第 6 个产品时查看控制台,您只会看到一条额外的“已调用”消息。

作为this.bgClass的值仅在 ngOnInit 期间读取你的指令的钩子(Hook),只有新的 <tr>实例将显示为黄色。

关于javascript - 为什么数据绑定(bind)不适用于我的自定义属性指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58550266/

相关文章:

javascript - 传递 HTML 输入表单内容进行计算

javascript - HTML5 : Canvas performs too slow on lower end computers

javascript - 如何仅显示 mat-table 中第一行的按钮

angular - 为什么异步管道的新数据不会导致数据重新渲染?

javascript - TypeError : this. props.weather 未定义

javascript - AngularJs - 在 Controller 中的 $http 调用中设置 'this' 对象?

angular - 如何在 Angular 8/9/10/11 中访问可重用组件中的子模板

javascript - Angular 模块/组件 - 单独显示以及在另一个模块/组件内显示?

angular - 如何在 apache Tomcat8 服务器中部署 Spring boot 后端和 Angular 6 前端应用程序?

javascript - 如何描述传递的匿名函数的参数?