javascript - 为什么数据绑定不适用于我的自定义属性指令
问题描述
下面是我的代码,我省略了组件代码的缩写:
模板.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 应该是黄色的,不是吗?那么为什么只有第六项是黄色的呢?
解决方案
我没有做很多 Angular,但这看起来就像我期望的代码一样。每次通过循环 ( ) 时,由于属性中的逻辑,let item of getProducts()
前 5行<tr>
(表行)将应用该类,除了应用之外的所有内容。bg-success
[pa-attr]
bg-warning
推荐阅读
- python - 如何在python中从.mat文件(另存为-v7.3)加载所有变量?
- google-chrome - 找不到 sslauncher:///?ssurl=url Chrome Fedora SSLauncher 的任何应用程序或处理程序
- flutter - Flutter 中的 Nexus 5 全屏尺寸太小?
- ios - 用颤振恶搞定位 iPhone
- mysql - MySQL CLI 客户端更改套接字位置
- html - 根据图形创建带有标题和表单的垂直导航栏
- c++ - 如何修复 EFI_DEVICE_ERROR
- android - 单击按钮时,将多个值从 recyclerview 传递到主要活动
- node.js - 在树莓派上安装 node.js 12 时出现依赖错误
- javascript - 我已经完成了我的网站但没有保护?