javascript - angular 5 - 仅当数组中存在元素时才添加类

标签 javascript angular ng-class

在使用 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/

相关文章:

javascript - ng-class 在点击事件时删除类

Angular2 异常 : ngClass within a Host, "isn' t 一个已知的原生属性”

javascript - 如何使其他指令在 uib-tab 元素内工作

javascript - nodejs mongoose 删除命中错误 : Can't set headers after they are sent

angular - 使用 cypress 从 Mat-select 中选择选项

angular - 导入的模块是否捆绑到 Angular 中的模块 block 文件中

typescript - Angular 2 服务没有被注入(inject)到组件中

angular - 在 Angular2 中有条件地分配类

c# - 禁用内容页中母版页的超链接

javascript - js数+1问题