Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 - add class only if element exists in array

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 compiling.

note that the "favoriteList" may be load to the page after "products".

Any idea how can I do this?

thanks!

like image 292
levi Avatar asked Aug 22 '18 10:08

levi


1 Answers

problem is in your some() method,

Here's is an example

component.html

<div *ngFor="let p of products" [class.Flag]="someMethod(p.id)"> {{p.name}} 
</div>

component.css

.Flag { background: red; }

and 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);
  }

here is Stackblitz demo.

like image 52
Aniket Avhad Avatar answered Nov 12 '22 08:11

Aniket Avhad