【问题标题】:CSS td conditional background color settingCSS td 条件背景色设置
【发布时间】:2020-06-12 16:03:23
【问题描述】:

假设我有以下角度表

  <table>
    <tr *ngFor="let company of investTable; let i = index">
      <td>
       {{company.name}}
      </td>
      <td>
       {{company.price}}
      </td>
      <td>
       {{company.profit}}
      </td>
    </tr>
  </table>

如何制定一个简洁的解决方案,让表格单元格根据单元格值具有背景颜色?可以说,如果公司利润为正,则将其设为绿色。

【问题讨论】:

    标签: css angular html-table conditional-statements background-color


    【解决方案1】:

    在css中

    td.highlight {
      background-color: green;
    }
    

    在 html 中:-

    <table>
        <tr *ngFor="let company of investTable; let i = index">
          <td>
           {{company.price}}
          </td>
          <td [ngClass]="{'highlight': company.profit > 0}">
           {{company.profit}}
          </td>
        </tr>
      </table>
    

    【讨论】:

      【解决方案2】:

      您可以将其添加到您的 html 中:

      &lt;td [style.positive]="company.profit &gt; 0"&gt;

      这是你的CSS:

      td.positive{
        background-color: green;
      }
      

      【讨论】:

        【解决方案3】:

        查看ngStyle 和ngClass。最简单的用例是直接绑定到 style 属性。

        <table>
          <tr *ngFor="let company of investTable; let i = index">
            <td>
              {{company.name}}
            </td>
            <td>
              {{company.price}}
            </td>
            <td [style.background-color]="company?.profit > 5 ? 'green' : 'red'">
              {{company.profit}}
            </td>
          </tr>
        </table>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-21
          • 2014-03-20
          • 2022-12-29
          • 2021-07-09
          • 2020-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多