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

Angular Material表格中如何为status列值为Missing的元素设置样式

实现方案

你可以选择以下两种方式实现需求,推荐第一种,可读性和可维护性更高:

方案1:单独定义status列(推荐)

把需要特殊渲染的status列从通用循环中抽出来单独定义,其余列保持通用循环逻辑:

<table mat-table
       [dataSource]="dataSource" multiTemplateDataRows
       class="mat-elevation-z8">
  <!-- 渲染除status外的通用列 -->
  <ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns.filter(col => col !== 'status')">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <!-- 单独写status列的渲染逻辑 -->
  <ng-container matColumnDef="status">
    <th mat-header-cell *matHeaderCellDef> status </th>
    <td mat-cell *matCellDef="let element">
      <mat-chip *ngIf="element.status === 'Missing'" style="background-color: #ec9d9d; color: red">Missing</mat-chip>
      <ng-container *ngIf="element.status !== 'Missing'">
        {{element.status}}
      </ng-container>
    </td>
  </ng-container>

  <!-- 保留你原有表格的行定义代码即可 -->
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

方案2:通用循环内加列判断

不拆分列循环,在单元格渲染时判断当前列是否为status列,走对应逻辑:

<table mat-table
       [dataSource]="dataSource" multiTemplateDataRows
       class="mat-elevation-z8">
  <ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element">
      <ng-container *ngIf="column === 'status'; else renderCommonColumn">
        <mat-chip *ngIf="element.status === 'Missing'" style="background-color: #ec9d9d; color: red">Missing</mat-chip>
        <ng-container *ngIf="element.status !== 'Missing'">
          {{element.status}}
        </ng-container>
      </ng-container>
      <ng-template #renderCommonColumn>
        {{element[column]}}
      </ng-template>
    </td>
  </ng-container>

  <!-- 保留你原有表格的行定义代码即可 -->
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

注意事项

你原有代码存在语法错误:同一个ng-container上不能同时使用*ngIf和*ngFor两个结构型指令,且*ngIf表达式内不需要加{{}}插值符,直接写变量即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:15:04