html - 根据不同的英雄超能力为表格的行添加特定的颜色
问题描述
我想确保表格的行具有基于英雄超能力的颜色。比如英雄拥有超强实力,其行颜色为color: red,如果是FLying 行颜色为color: blue
我无法将数据绑定在一起并根据英雄超能力创建行颜色。
<table>
<tr>
<th>Hero ID</th>
<th>Hero Name</th>
<th>Gender</th>
<th>Age</th>
<th>Superpower</th>
<th>Delete</th>
</tr>
<tr *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
<td><span class="badge">{{hero.id}}</span></td>
<td><span class="badge">{{hero.name}}</span></td>
<td><span class="badge">{{hero.gender}}</span></td>
<td><span class="badge">{{hero.age}}</span></td>
<td><span class="badge">{{hero.superpowers}}</span></td>
</a>
<td><button class="delete" title="delete hero" (click)="delete(hero)">X</button></td>
</tr>
</table>
解决方案
根据条件更改颜色的最佳方法可以使用如下ngStyle
指令。
组件.html
<tr *ngFor="let hero of heroes" [ngStyle]="{'background-color':getColor(hero.superpowers)}" >
<a routerLink="/detail/{{hero.id}}">
<td><span class="badge">{{hero.id}}</span></td>
<td><span class="badge">{{hero.name}}</span></td>
<td><span class="badge">{{hero.gender}}</span></td>
<td><span class="badge">{{hero.age}}</span></td>
<td><span class="badge">{{hero.superpowers}}</span></td>
</a>
<td><button class="delete" title="delete hero"
(click)="delete(hero)">X</button></td>
</tr>
组件.ts
getColor(superpower) {
console.log(superpower);
switch (superpower) {
case 'strength':
return 'red';
case 'FLying':
return 'blue';
}
}
希望这会有所帮助!
推荐阅读
- c# - 如何修复 .NET Core 中 Startup.cs 类中的依赖注入错误
- javascript - React 组件不显示内容
- mongodb - MongoDB/Mongoose 聚合与查找、嵌套数组、排序
- ionic-framework - Ionic 3:如何从 RadioButton 中仅获取选定的值?
- azure - 使用 Azure EventHubs 调用 ADF 管道
- reporting-services - 无法在 Visual Studio 2017 中添加 Crystal Report
- git - Git:如何确保我不会将哈希提交/推送到尚未推送到远程的子模块?
- spring - Ehcache - 用于 removeAll 操作的磁盘持久缓存的 java.io.EOFException
- conv-neural-network - 单个cnn如何预测YOLO中的bounding box坐标、objectness score和概率?
- css - 如何增加输入文件元素的面积?