角度如何样式化表格中的最小值

时间:2019-07-04 14:06:21

标签: angular ng-class

我在Angular中有一个表格,其中显示了带有价格的商品列表。价格是根据数据库排序的,因此始终以最低价格为准。我想为出价金额列的第一行设置不同的样式(绿色)(默认情况下,所有其他行均为红色,因此我只需要对第一行进行样式设置)。 另一个问题是,我需要显示最低出价与其他出价之间的差异(将添加图片以使其更加理解) stackblitz链接: https://stackblitz.com/edit/angular-lxngez 预期结果: https://imgur.com/a/TpJwHuW

我尝试为第一个出价索引添加 ngClass 。 TotalPrice,但是没有用:

<td [ngClass]="{'green-text': bid.TotalPrice[0]}">{{ bid.TotalPrice | currency }}</td>

我添加了图片以获得预期的效果(两件事是我需要实现不同的样式以及最低价格与其他价格之间的差异。

5 个答案:

答案 0 :(得分:1)

对于颜色,您可以完全在CSS中完成。您可以在表格单元格中添加.price类并添加一条规则,该规则选择表格的第一行并覆盖价格单元格颜色

在模板中:

<td style="color: red" class="price input-text">{{ bid.TotalPrice | currency }}</td>

在CSS中:

#tableSortExample tbody tr:first-of-type .price {
   color: green!important;
}

关于价格,您可以在最低价格和其他情况下简单地添加条件跨度

<td style="color: red" class="price input-text">{{ bid.TotalPrice | currency }}
    <span *ngIf="i === 0"> Lowest price.</span>
    <span *ngIf="i > 0"> {{bid.TotalPrice - auctionBidsData.auctionBids[0].TotalPrice | currency}}</span>
</td>

答案 1 :(得分:1)

让我们尝试一下(纯角度实现):

HTML

    <td style="color: red" class="input-text"
        [ngClass]="{ 'price-input-text': 'i == 0' }"
        [ngStyle]="{color: i == 0 ? 'green' : 'red'}">
      {{ bid.TotalPrice | currency }}
      <small *ngIf="i == 0">Lowest price</small>
    </td>

答案 2 :(得分:0)

像这样使用ngClass:

<td [ngClass]="{ low: i == 0, high: i > 1, other: condition(item, i) }">ABC</td>

它将为第二行上方的所有内容添加第一个索引类low的类high,为条件被评估为true的那些对象添加类other

只需使用这些类进行相应的样式设置即可。 example

答案 3 :(得分:0)

您可以使用 [ngClass] 如下进行操作。

HTML

<tr *ngFor="let bid of auctionBidsData.auctionBids; let i = index" class="pointer-hover"
    (click)="goToLiveAuction(auction.UID)">
  ...
  <td style="color: red" class="input-text" 
      [ngClass]="{ 'lowest': i === 0 }">{{ bid.TotalPrice | currency }}</td>
  ...
</tr>

CSS

.lowest {
  color: green !important;
  font-weight: bold;
}

StackBlitz Demo

答案 4 :(得分:0)

使用reduce找出最小值

this.minPrice=this.auctionBidsData.auctionBids.reduce(
        (min,b)=>min<b.TotalPrice?min:b.TotalPrice,
           this.auctionBidsData.auctionBids[0].TotalPrice) 

并在td中使用

 [style.color]="{bid.totalPrice==minPrice?'green':null"}