最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angular 5 - add class only if element exists in array - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 3

problem 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

发布评论

评论列表(0)

  1. 暂无评论