首页 > 解决方案 > 如何在 Angular 中对来自 api 的数据设置正面、负面和中性颜色和图标

问题描述

我想通过 API 设置我的数据,使其看起来像它在股票市场上的显示方式 在此处输入图像描述

正数变为绿色加图标,负数变为红色和向下图标,中性为带有向上和向下图标的黄色阴影。我尝试使用列表,但它不能正常工作尝试使用表仍然是相同的输出。我怎样才能做到这一点?

到目前为止我用一张桌子做了什么

                      <table class="table" id="htmlData">
                          <thead class="thead">
                          </thead>
                          <tbody class="list-group">

                          <tr class="list-group-item">
                            <td
                              style="vertical-align:bottom; text-align:left; font-size: 2em;font-weight: bold;color:white">
                              UMME
                            </td>
                            <td
                              style="vertical-align:bottom; text-align:left; font-size: 2em;font-weight: bold;color:white">{{report.umme | number : '1.2-2'}}
                              %
                            </td>
                            <td class="warning"
                                style="vertical-align:bottom; text-align:left; font-size: 2em;font-weight: bold;color:white"
                                [ngStyle]="{'background-color' : (report.umme_daily_change > 0) ? 'green': 'red' }">
                              {{report.umme_daily_change | number : '1.4-4'}}</td>
                            <td
                              style="vertical-align:bottom; text-align:left; font-size: 2em;font-weight: bold;color:white"
                              [ngStyle]="{'background-image' : (report.umme_daily_change > 0) ? getIncrease():  getDecrease() }"
                              style="background-repeat: no-repeat"></td>
                          </tr>
                          

                          </tbody>
                        </table>

标签: angulartypescript

解决方案


您应该将所有三种颜色样式提取到 css 并在 css 类上使用条件

<td
 [class.colorRed]="umme_daily_change < 0"
 [class.colorNeutral] = "umme_daily_change === 0"
 [class.colorPositive] = "umme_daily_change > 0
></td>

.colorRed{
  background-color: red;
}
.colorNeutral{
  background-color: yellow;
}
.colorPositive{
  background-color: green;
}

使用该语法,在 html 元素上设置满足以下条件的类。


推荐阅读