将 css 分配给 *ngFor 项的值
Posted
技术标签:
【中文标题】将 css 分配给 *ngFor 项的值【英文标题】:Assign css to value of *ngFor item 【发布时间】:2019-06-18 17:15:00 【问题描述】:我的 ion-item 会显示以下警报、1 级、2 级或 3 级紧急情况之一。
<ion-item text-wrap *ngFor="let item of levelofEmergency">
item.level
</ion-item>
我要做的是根据关卡的文本分配css。即警报为灰色,1 级为绿色等。
<ion-item text-wrap *ngFor="let item of statuslevelEmergency">
<span style="color:red" *ngIf="item.level === 'Alert'">item.level</span>
</ion-item>
在此先感谢您为我指明正确方向的任何信息。
【问题讨论】:
你不能使用两个这样的结构指令(*ngFor + *ngIf),你可以在style
属性上添加表达式,比如:item.level === 'Alert' ? 'red' : ''
【参考方案1】:
您可以在具有索引签名的对象中定义级别颜色:
levelColors: [level: string]: string =
Alert: "grey",
Level1: "green",
Level2: "blue",
Level3: "orange",
Emergency: "red",
;
并像关联数组一样使用它来设置color
属性与style binding:
<ion-item text-wrap *ngFor="let item of items" [style.color]="levelColors[item.level]">
<span>item.level</span>
</ion-item>
请参阅this stackblitz 以获取演示。
使用Map
对象可以获得相同的结果:
levelColors = new Map<string, string>([
["Alert", "grey"],
["Level1", "green"],
["Level2", "blue"],
["Level3", "orange"],
["Emergency", "red"],
]);
在模板中使用稍微不同的语法:
<ion-item text-wrap *ngFor="let item of items" [style.color]="levelColors.get(item.level)">
<span>item.level</span>
</ion-item>
请参阅this stackblitz 以获取演示。
【讨论】:
【参考方案2】:可以绑定样式,然后添加条件逻辑
<ion-item text-wrap *ngFor="let item of statuslevelEmergency">
<span [style.color]="item.level === 'Alert' ? 'red' : 'green'">item.level</span>
</ion-item>
另请参阅 Angular 文档中的 Style binding。
如果您想要一个动态类(如在样式表中找到的),请参阅之前的答案:Angular: conditional class with *ngClass
【讨论】:
@ThomasDegroot - 您从未说明每个级别的其他颜色应该是什么,但我希望这足以让您自己添加它们。您可以根据需要继续链接,也可以将整个内容移到组件中,并使用一个名为getColorForAlert(level: string):string
(或类似名称)的方法,然后调用它。以上是关于将 css 分配给 *ngFor 项的值的主要内容,如果未能解决你的问题,请参考以下文章