[Fixed] How to display nested objects from array in Angular Typescript

Issue

I have this array :

grp = [ {model: "CF650-3C", color: {Orange: 3, Black: 2} }, {model: "HD4533F", color: {Black: 2, Orange: 1} } ]

Those are objects in there that have .model and .color properties and I want to display them in a table so I need access to all .color values in there individually.
So far I’ve tried iterating over like this:

<table class="table table-striped" >
<thead>
  <tr  >
    <th scope="col">Model</th>
    <th scope="col">color</th>
  </tr>
</thead>
<tbody>
  <ng-container *ngFor="let g of grp">
  <tr >
   
    <td>{{ g.model }}</td>
    <td>{{ g.color | json }}</td>

  </tr>
</ng-container>
</tbody>

Problem is it gets displayed like this and I don’t know how to access the different .color keys and values

CF650-3C    { "Orange": 3, "Black": 2 } 
HD4533F     { "Black": 2, "Orange": 1 } 

Solution

Some practices you can use:

Iterating the values by using keyvalue pipe

  <ng-container *ngFor="let g of grp">
  <tr >
    <td>
     <div *ngFor="let c of g.color | keyvalue">
      Key: <b>{{c.key}}</b> and Value: <b>{{c.value}}</b>
     </div>
    </td>
    <td>{{ g.model }}</td>
  </tr>
 </ng-container>

Create a component and set your object as @input StackBlitz

  <ng-container *ngFor="let g of grp">
  <tr >
    <td>
     <app-color [Color]="g.color"></app-color>
    </td>
    <td>{{ g.model }}</td>
  </tr>
 </ng-container>

Create a custom pipe that return a value based on your object UltimateCourses

  <ng-container *ngFor="let g of grp">
  <tr >       
    <td>{{ g.model }}</td>
    <td>{{ g.color | mycolorpipe }}</td>    
  </tr>
</ng-container>

Leave a Reply

(*) Required, Your email will not be published