在使用 ng-for
循环时,我想将类添加到项目,前提是项目的 id 存在于其他一些对象列表中。
我试过这样的:
<div *ngFor="let p of products" [class.Flag]="favoriteList.some((item)=> item.Id == p.id)"> </div>
或者这个:
<div *ngFor="let p of products" [ngClass]="favoriteList.some((item)=> item.Id == p.id) ? 'Flag': ''"> </div>
但它没有编译。
请注意,“favoriteList”可能会在“products”之后加载到页面。
知道我该怎么做吗?
谢谢!
最佳答案
问题出在你的some()方法上,
举个例子
component.html
<div *ngFor="let p of products" [class.Flag]="someMethod(p.id)"> {{p.name}}
</div>
component.css
.Flag { background: red; }
和component.ts
products = [
{"id": 1 , name: 'abc'},
{"id": 2 , name: 'xyz'}
];
favoriteList = [
{"id": 1 , name: 'test'},
{"id": 3 , name: 'test1'}
];
someMethod(id){
return this.favoriteList.some((item) => item.id == id);
}
这里是 Stackblitz演示。
关于javascript - angular 5 - 仅当数组中存在元素时才添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964861/