如何动态更改条件[ngClass]

时间:2019-03-22 13:35:29

标签: angular angular6

我想将一个类动态分配给表中的特定单元格。

<td *ngFor="let col of cols" [ngClass]="col.condition">

“ cols”中的对象可能如下所示:

{condition: '{\'prio-high\': priority == 0}', noCondition: 'prio-high'}

我确保优先级的确是== 0。

这甚至可能吗?以下示例可以正常工作。如果我想使用条件,它似乎不起作用。

<td *ngFor="let col of cols" [ngClass]="col.noCondition">

示例:

.html

<style>
  .condition{background-color: red}
  .noCondition{background-color: blue}
  .someRandomOtherCondition{background-color: orange}
</style>

<div *ngFor="let o of objects" [ngClass]="o.template">
  {{ o.name }} has priority {{ o.prio }}
</div>  

.ts

export class AppComponent  {

  info = [
      {object1: 'noCondition'},
      {object2: '{\'condition\': prio == 0}'}
    ]

  objects = [
    {
      name: 'object1',
      prio: 0, //imagine this number is being dynamically assigned and we don't know the value beforehand
      template: 'noCondition'
    },
    {
      name: 'object3',
      prio: 0, //imagine this number is being dynamically assigned and we don't know the value beforehand
      template: 'someRandomOtherCondition'
    },
    {
      name: 'object2',
      prio: 1, //imagine this number is being dynamically assigned and we don't know the value beforehand
      template: '{\'condition\': prio == 1}'
    }
  ];

}

如果运行此示例,您将看到object2从未正确格式化。

stackblitz:https://stackblitz.com/edit/angular-dani1p

2 个答案:

答案 0 :(得分:1)

您可以使用相同的变量测试不同的情况,例如

组件

  state : number=0;

  ngOnInit() {
    setInterval( () => {
      this.state = Math.floor(Math.random() * 15)
    },2000)
  }

模板

<p [ngClass] ="{red: state < 5,green : state >=5 && state <=7 , blue : state > 7 }">
  O.o => {{state}}  something magical happen :)
</p>

Demo

因此,您可以将ngClass更新为类似

<ul>

  <li *ngFor="let col of cols" 
    [ngClass]="{red:col.priority == 0,green: col.priority == 1,blue:  col.priority==3}">
            {{col.name}} priority => {{col.priority}}
        </li>
    </ul>

Demo

已更新!

我们需要评估字符串条件,其中条件包括对象的属性(如变量),这使我想起[with][3]语句,到目前为止,您无法使用with语句,但我想通过使用Function constructorobject destructor得到相同的结果,结果看起来像这样

  public getCondition(obj, condition) {
    const props = Object.keys(obj).reduce( (acc, next) => `${acc} , ${next}`);
    const evalCon = new Function(` return function ({${props}})  { return ${condition}} `);
    return evalCon()(obj)
  }

模板

<ul>
    <li *ngFor="let obj of objects" [ngClass]="getCondition(obj,obj.template)" >
        {{obj.name}} 
    </li>
</ul>

Demo

答案 1 :(得分:0)

NgClass可以与if语句一起使用,以明确地分配类。

这里是一个示例,如果您要在条件"prio-high"等于0时分配类col.noCondition

<td *ngFor="let col of cols" [ngClass]="{'prio-hight' : col.noCondition == 0}">