0

I am having dynamic mat table to show json response which i am receiving from rest api. I want to change the cell color based on some condition. But, If i try to apply [ngStyle] it's applying for the whole row. I want to apply it only for a particular cell,

  <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 structure:

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

In that above structure "col 1" is for display the values in the table and "col 2" is a value to change the color code of particular row

Anyone help will be appreciated!!!!

S.M.Priya
  • 354
  • 4
  • 15

1 Answers1

1

You can do some thing like this, change your ngStyle as

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

Example

enter image description here

In 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>  

Hope this helps!

Goskula Jayachandra
  • 3,931
  • 2
  • 12
  • 22