You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中为包含指定内容的表格特定行应用样式?

Got it, let's figure out how to add that net-cost class to your specific rows in Angular! Here's a straightforward solution using Angular's built-in directives:

Adding Conditional Class to Target Rows in Angular *ngFor

Step 1: Use [ngClass] for Dynamic Styling

Angular's [ngClass] directive lets you apply CSS classes based on a condition. We'll check if the first cell of each row matches "Net Premiums Written", then apply the net-cost class to both the <tr> and all its <td> elements (just like your expected output).

Modified Template Code

<tbody>
  <tr 
    *ngFor="let row of fsIncomeStatementTable | slice:1"
    [ngClass]="{'net-cost': row[0] === 'Net Premiums Written'}"
  >
    <td 
      style="padding:6px 10px; border-bottom: 1px solid #d8d8d8;"
      [ngClass]="{'net-cost': row[0] === 'Net Premiums Written'}"
    >
      {{row[0]}}
    </td>
    <td 
      *ngFor="let cell of row | slice:1"
      style="padding:6px 10px; border-bottom: 1px solid #d8d8d8;"
      [ngClass]="{'net-cost': row[0] === 'Net Premiums Written'}"
    >
      {{cell | shortAndBlankNumberFormat: 2}}
    </td>
  </tr>
</tbody>

How It Works

  • The condition row[0] === 'Net Premiums Written' checks if the first value in the current row array is exactly the text we're targeting.
  • When the condition is true, the net-cost class is applied to the <tr> and every <td> inside it, which matches your desired result.

Cleaner Alternative: Move Condition to a Component Method

If you think you might reuse this check later, or if the logic gets more complex, you can extract it to a component method for better maintainability:

In your component TypeScript file:

isNetPremiumRow(row: any[]): boolean {
  return row[0] === 'Net Premiums Written';
}

Then update your template to use this method:

<tbody>
  <tr 
    *ngFor="let row of fsIncomeStatementTable | slice:1"
    [ngClass]="{'net-cost': isNetPremiumRow(row)}"
  >
    <td 
      style="padding:6px 10px; border-bottom: 1px solid #d8d8d8;"
      [ngClass]="{'net-cost': isNetPremiumRow(row)}"
    >
      {{row[0]}}
    </td>
    <td 
      *ngFor="let cell of row | slice:1"
      style="padding:6px 10px; border-bottom: 1px solid #d8d8d8;"
      [ngClass]="{'net-cost': isNetPremiumRow(row)}"
    >
      {{cell | shortAndBlankNumberFormat: 2}}
    </td>
  </tr>
</tbody>

This keeps your template tidy and makes the condition easier to adjust or reuse across your component.

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:07:05