下面是我的代码,省略组件代码缩写:
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");
}
}
我在这里很困惑,为什么只有第六项的颜色更改为黄色(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/