6

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!

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

5 Comments

same question that i asked @Suresh Kumar Ariya
Yes, it will call getClass function whenever products list is being updated.
yes, but my problem is that maybe "products" will load before "favoriteList". and than the function "getClass" will always return false. because "favoriteList" is still empty
so initialize favoriteList in constructor as blank. And whenever you are getting result for favList from api reassign products list from existing. It will work.
You can do it in another way as well, add favourite in product object when you receive data from api.
0

Might been an issue with the ngClass Syntax. Here is the stackblitz code https://stackblitz.com/edit/angular-3zfrrs

1 Comment

thanks! but when the "check()" will call? while the page loading? i asking because my list come from a server during the page load. so if the "check()" function will call before the list will be ready, it's will not work well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.