angular - 如何动态更改条件 [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
解决方案
您可以使用相同的变量测试不同的案例,如下所示
零件
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 constructor
object 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>
推荐阅读
- kubernetes - 如何在自定义 VPS 上安装 Hasura 平台?
- c# - 在没有本机类的 xamarin.forms 中使用 FCM
- user-interface - 在模态对话框中修改“标题”
- chart.js - 我在chartsjs上搜索附加选项
- node.js - Async/Await 不适用于节点 4.x。我可以有替代品吗?
- mysql - 如何从托管在 Google App Engine 上的 React App 连接到 Google SQL?
- nullpointerexception - 当详细信息带将拆分类型作为阻止时,JasperReport 获取 NullPointerException
- javascript - 如何在 jquery 中获得警报框?
- android - 为什么我得到空的 json 结果
- ios - 操作表或警报可以具有交互元素吗?