首页 > 解决方案 > 如何动态更改条件 [ngClass]

问题描述

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

<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 从未按应有的格式正确格式化。

堆栈闪电战: https ://stackblitz.com/edit/angular-dani1p

标签: angularangular6

解决方案


您可以使用相同的变量测试不同的案例,如下所示

零件

  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>

演示

所以对于你的情况,你可以将 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>

演示

更新!

我们需要评估字符串条件,其中条件包括对象的属性,如变量,这提醒我[with][3]声明到目前为止你不能使用语句,但我可以通过使用andwith来获得相同的结果,结果看起来像这个⬇</p> 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>

演示


推荐阅读