首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据不同的英雄超能力向表的行添加特定颜色。

根据不同的英雄超能力向表的行添加特定颜色。
EN

Stack Overflow用户
提问于 2019-03-25 07:25:56
回答 2查看 61关注 0票数 2

我想确保表中的行都有基于英雄超能力的颜色。例如,如果英雄有超能力,它的行颜色将为:红色,如果FLying行颜色为:蓝色。

我不能将数据绑定在一起,创建基于英雄超能力的行颜色。

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-25 07:36:29

根据条件更改颜色的最佳方法,您可以使用ngStyle指令,如下所示。

component.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
  getColor(superpower) {
    console.log(superpower);
    switch (superpower) {
      case 'strength':
        return 'red';
      case 'FLying':
        return 'blue';
    }
  }

下面是stackblitz的演示

希望这能帮上忙!

票数 3
EN

Stack Overflow用户

发布于 2019-03-25 07:32:28

您可以使用ngStyle,如下所示

代码语言:javascript
复制
<tr *ngFor="let hero of heroes" 
[ngStyle]="{'background-color': hero.superpowers == 'flying'? 'blue': 'red' }">
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55332957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档