簡體   English   中英

如何根據表格單元格中的值更改表格行的背景顏色?

[英]How to change the background color of table row based on value in table cell?

我正在使用Angular *ngFor指令生成動態表。 這是下面的結構:

       <tr *ngFor = 'let element of ph'>
            <td>{{element.timestamp}}</td>
            <td>{{element.ph}}</td>                   
       </tr>

生成的表的示例圖像如下所示。 圖片范例

我想為包含20 <PH值<50的整個表行上色。我該怎么做?

如果值就是您想要的值,則可以使用[ngClass]並應用一個類。

在這里,使用這個:

<table border="1">
  <thead>
    <td>Reading Time</td>
    <td>PH</td>
  </thead>
  <tbody>
    <tr *ngFor='let element of ph'
      [ngClass]="{'color': (element.ph > 20 && element.ph < 50)}">
      <td>{{element.timestamp}}</td>
      <td>{{element.ph}}</td>
    </tr>
  </tbody>
</table>

另外,根據Yoel Rodriguez的建議,您還可以使用[class.color]動態應用它:

<table border="1">
  <thead>
    <td>Reading Time</td>
    <td>PH</td>
  </thead>
  <tbody>
    <tr *ngFor='let element of ph'
      [class.color]='element.ph > 20 && element.ph < 50'>
      <td>{{element.timestamp}}</td>
      <td>{{element.ph}}</td>
    </tr>
  </tbody>
</table>

這是color css類:

.color {
  color: white;
  font-weight: bold;
  background-color: red;
}

示例堆棧

PS:我不建議使用[ngStyle]方法,因為編寫內聯樣式並不是真正的好習慣。

您可以在ph列上簡單地使用NgClass指令。 就像是:

<td [ngClass]="{'first': true, 'second': true, 'third': false}">{{element.ph}}</td>

換句話說,如果您的條件為真,請使用具有特定樣式的特定類。

希望能幫助到你!

您可以使用[ngClass] ,但[ngStyle]更適合於小的樣式更改:

<div [ngStyle]="{<property>: <value>}">

對於您的特殊情況:

<tr [ngStyle]="{'background-color': (20<ph && ph<50) ? 'red' : 'white'}">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM