While using ng-for
loop, I want to add class to item, only if the id of the item exists in some other objects list.
I tried something like this:
<div *ngFor="let p of products" [class.Flag]="favoriteList.some((item)=> item.Id == p.id)"> </div>
or this:
<div *ngFor="let p of products" [ngClass]="favoriteList.some((item)=> item.Id == p.id) ? 'Flag': ''"> </div>
But it's not piling.
note that the "favoriteList" may be load to the page after "products".
Any idea how can I do this?
thanks!
While using ng-for
loop, I want to add class to item, only if the id of the item exists in some other objects list.
I tried something like this:
<div *ngFor="let p of products" [class.Flag]="favoriteList.some((item)=> item.Id == p.id)"> </div>
or this:
<div *ngFor="let p of products" [ngClass]="favoriteList.some((item)=> item.Id == p.id) ? 'Flag': ''"> </div>
But it's not piling.
note that the "favoriteList" may be load to the page after "products".
Any idea how can I do this?
thanks!
Share edited Aug 22, 2018 at 12:00 levi asked Aug 22, 2018 at 10:30 levilevi 1,1472 gold badges14 silver badges27 bronze badges3 Answers
Reset to default 3problem is in your some() method,
Here's is an example
ponent.html
<div *ngFor="let p of products" [class.Flag]="someMethod(p.id)"> {{p.name}}
</div>
ponent.css
.Flag { background: red; }
and ponent.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);
}
here is Stackblitz demo.
use ng-container
in order to access template variable in div
for class as:
<ng-container *ngFor="let p of products">
<div [ngClass]="getClass(p.id)">{{p.name}}</div>
</ng-container>
getClass(id) {
return this.favoriteList.some(item => item.Id == id) ? 'Flag':'';
}
Find stackblitz here
Solution 2:
<ng-container *ngFor="let p of products">
<div [ngClass]="{'flag': p.favourite == true}">{{p.name}}</div>
</ng-container>
update products with favourite
when you receive from api.
Might been an issue with the ngClass Syntax. Here is the stackblitz code https://stackblitz./edit/angular-3zfrrs