如何在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:
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-costclass 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

