【问题标题】:How to change the mat-cell color based on json response in Mat-Dynamic-Table Angular?如何根据 Mat-Dynamic-Table Angular 中的 json 响应更改 mat-cell 颜色?
【发布时间】:2020-05-12 16:48:29
【问题描述】:

我有动态 mat 表来显示我从 rest api 接收到的 json 响应。我想根据某些条件更改单元格颜色。但是,如果我尝试应用 [ngStyle] 它会申请整行。 我只想将它应用于特定的单元格

  <mat-table #table [dataSource]="dataSource">
    <ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
      <mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
      <mat-cell *cdkCellDef="let data" [ngStyle]="{'color': data.name == 'Boron' ? 'green':'red'}">{{ column.cell(data) }}</mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>

JSON 结构:

     [ 
         {
          "col1":   {"name":"Boron","grade":A15},
          "col2":   [A15],
         },
         {
          "col1":   {"name":"Hydrogen", "grade":A28},
          "col2":   ["Hydrogen"],
         },
         {
           "col1":   {"name":"Helium", "grade":A56},
           "col2":   ["Helium","A56"],
         },
     ]

在上面的结构中,“col 1”用于显示表中的值和 “col 2”是改变特定行颜色代码的值

任何人的帮助将不胜感激!!!!

【问题讨论】:

    标签: angular7 angular-material-table


    【解决方案1】:

    您可以这样做,将您的 ngStyle 更改为

    [ngStyle]="{'color': data.name == 'Boron' && column.header == "your table header name where you want this color" ? 'green':'red'}"
    

    示例

    在 HTML 中

     <ng-container *ngFor="let column of columnsDef">
    <ng-container [matColumnDef]="column.id">
      <th mat-header-cell *matHeaderCellDef> {{column.id}} </th>
      <ng-container *ngIf="!column.dynamicCellComponent">
        <td mat-cell *matCellDef="let element"  [ngStyle]="{'color':column.id=='position' && element.position==1 ? 'red':''}" > 
          {{element[column.id]}}
        </td>
      </ng-container></ng-container></ng-container>  
    

    希望这会有所帮助!

    【讨论】:

    • 你能和我分享一下这个stackblitz吗?
    • 在这里,您将列名“位置”和列值硬编码为“1”。对我来说,一切都应该是动态的。
    • 你说在某些情况下你应该改变颜色你能告诉我是什么情况或创建一个类似的 JSON,你能分享给我吗。
    • { "col1": {"name":"Boron","grade":A15}, "col2": [A15], },这里你需要改变的颜色是没错
    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2019-06-04
    • 2021-02-28
    相关资源
    最近更新 更多