我想确保表中的行都有基于英雄超能力的颜色。例如,如果英雄有超能力,它的行颜色将为:红色,如果FLying行颜色为:蓝色。
我不能将数据绑定在一起,创建基于英雄超能力的行颜色。
<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>发布于 2019-03-25 07:36:29
根据条件更改颜色的最佳方法,您可以使用ngStyle指令,如下所示。
component.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>component.ts
getColor(superpower) {
console.log(superpower);
switch (superpower) {
case 'strength':
return 'red';
case 'FLying':
return 'blue';
}
}希望这能帮上忙!
发布于 2019-03-25 07:32:28
您可以使用ngStyle,如下所示
<tr *ngFor="let hero of heroes"
[ngStyle]="{'background-color': hero.superpowers == 'flying'? 'blue': 'red' }">https://stackoverflow.com/questions/55332957
复制相似问题