0

I am getting data from JSON file instead of database. I am trying to give color to the Icon based on the value of status in JSON for example [if green? class1:class2] below is my code.

My HTML file

   <ng-container matColumnDef="status" [ngClass] = "{'color1': row.status === 
        'GREEN', 'color2': row.status === 'RED'}">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
        <td mat-cell *matCellDef="let row" class="color1">{{row.status}}</td>
        <td mat-cell *matCellDef="let row" class="color2">{{row.status}}</td>
    </ng-container>

Below is my JSON file.

    data:[
          {
           "name": "xyz",
           "address": "post",
           "status": "GREEN"
          },
          {
           "name": "xyz1",
           "address": "post1",
           "status": "RED"
           }
         ],
       "count" : 2
}

This is my CSS

.color1{
  color: green;
}

.color2{
  color: red;
}

** I could not able to change color of status icon. And I got this error **

ERROR TypeError: Cannot read property 'status' of undefined

1 Answers1

2

ngClass receive an object key-values, keys are possibles classess, and values are conditions to apply keys

you could use static check for every possible values of classes like this.

 <td mat-cell *matCellDef="let row" class="color1"
     [ngClass]="{
     'green': row.status === 'GREEN',
     'red': row.status === 'GREEN'">{{row.status}}</td>


other option for the same idea

<td mat-cell *matCellDef="let row"
[class.red] = "row.status === 'RED'"
[class.green] = "row.status === 'GREEN'" >
{{row.status}}
</td>

other way is using map objetc to define classes in your ts and access once from html like this typescript file

mapClass = {
  'GREEN': 'green',
  'RED': 'red' 
}

and html

 <td mat-cell *matCellDef="let row" class="{{mapClass[row.status]}}">{{row.status}}</td>

the last one is better if your possibles class values changes frecuently, using mapClass you only add new possibles value and define css class, html keep intact.

EDITING: I think you edit your original question and I answer that original question. Your current error in my opinion is because you are trying to use ngCLass with ngcontainer,try to use ngClass in td. I see you show double td inside container with diferent classes, without ngIf. If I understand rigth, using that way you should use ngIf to show row status once. Any way, check my previous answer and I hope to be helpful