交替行颜色角度材料表

新手上路,请多包涵

我想知道我如何定位 Angular Material Table 中的偶数/奇数行,以便我可以将偶数/奇数行设置为不同的背景颜色。

我设置了我的 ClaimFileHistoryDataSource 类:

 claimClientInformation: ClaimFileHistory[];
dataSource : ClaimFileHistoryDataSource;
displayedColumns = ['TypeImg', 'Description', 'Agent'];

export class ClaimFileHistoryDataSource extends DataSource<ClaimFileHistory> {

    constructor(private _claimFileHistory: ClaimFileHistory[]) {
      super();
    }

    connect(): Observable<ClaimFileHistory[]> {
      return Observable.of(this._claimFileHistory);
    }

    disconnect() {}
}

NgInit 我打电话给我的服务去获取我需要的数据并填充 DataSource

 this._claimFileHistoryService.getClaimFileHistoryById().subscribe(response => {
  this.claimClientInformation = response;
  this.dataSource = new ClaimFileHistoryDataSource(this.claimClientInformation);
});

这很好,数据会按预期返回。

在 HTML 中 Mat-Table 看起来像这样:

     <mat-table #table [dataSource]="dataSource">

      <ng-container matColumnDef="TypeImg">
        <mat-cell *matCellDef="let row"><img [src]='row.TypeImg' height="40px"></mat-cell>
      </ng-container>

      <ng-container matColumnDef="Description">
        <mat-cell *matCellDef="let row">
          <div>
            <span class="d-block">{{row.Description}}</span>
            <span class="d-block">{{row.Date}}</span>
          </div>

        </mat-cell>
      </ng-container>

      <ng-container matColumnDef="Agent">
        <mat-cell *matCellDef="let row"> {{row.Agent}} </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>

我再次想知道如何获取表格的奇数/偶数行并将它们设置为不同的行背景颜色?

原文由 Ben Clarke 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 441
2 个回答

在 .css 或 .scss 文件中使用 Following CSS 为偶数/奇数行设置不同的样式:

 .mat-row:nth-child(even){
    background-color: red;
}

.mat-row:nth-child(odd){
    background-color: black;
}

原文由 mohit uprim 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用更新的方法为可能遇到此问题的未来开发人员更新此答案。

Material Angular 现在为行索引提供了一些变量。

 <mat-row *matRowDef="
              let row;
              let even = even;
              columns: displayedColumns;"
         [ngClass]="{gray: even}"></mat-row>

在你的 CSS 文件中: .gray { background-color: #f5f5f5 }

There are other properties like: index , count , first , last , even and odd

您可以在 Angular Docs 上找到更多信息,更具体地说,在“显示每行上下文属性的表格”部分

原文由 Gustavo Lopes 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题