如何在 Angular Typescript 中显示数组中的嵌套对象

How to display nested objects from array in Angular Typescript

我有这个数组:

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

其中的对象具有 .model 和 .color 属性,我想将它们显示在 table 中,因此我需要单独访问其中的所有 .color 值。 到目前为止,我试过像这样迭代:

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

问题是它像这样显示,我不知道如何访问不同的 .color 键和值

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

您必须遍历颜色对象 *ngFor="设 c 为 g.color"

您可以使用的一些做法:

使用

迭代值
  <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>

创建一个组件并将对象设置为@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>

创建一个自定义管道,return 一个基于您的对象的值 UltimateCourses

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

你可以这样做:

<ng-container *ngFor="let g of grp">
  <tr >
   
    <td>{{ g.model }}</td>
    <td>{{ Object.keys(g.color) }}</td>

    <td>{{ Object.values(g.color) }}</td>

  </tr>
</ng-container>