首页 > 解决方案 > 根据不同的英雄超能力为表格的行添加特定的颜色

问题描述

我想确保表格的行具有基于英雄超能力的颜色。比如英雄拥有超强实力,其行颜色为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>

标签: htmlcssangular

解决方案


根据条件更改颜色的最佳方法可以使用如下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';
    }
  }

这是关于 stackblitz 的演示

希望这会有所帮助!


推荐阅读