【问题标题】:How to display nested objects from array in Angular Typescript如何在Angular Typescript中显示数组中的嵌套对象
【发布时间】:2021-06-15 23:25:29
【问题描述】:

我有这个数组:

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

这些是其中具有 .model 和 .color 属性的对象,我想将它们显示在表格中,因此我需要单独访问其中的所有 .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 } 

【问题讨论】:

    标签: angular typescript dictionary nested iteration


    【解决方案1】:

    您可以使用的一些做法:

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

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

    创建一个自定义管道,该管道根据您的对象 UltimateCourses 返回一个值

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

    【讨论】:

      【解决方案2】:

      你可以这样做:

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

      【讨论】:

        【解决方案3】:

        你必须遍历颜色对象 *ngFor="let c of g.color"

        【讨论】:

          猜你喜欢
          • 2021-08-25
          • 2018-09-24
          • 2020-12-14
          • 1970-01-01
          • 1970-01-01
          • 2018-01-27
          • 2019-02-27
          • 2017-09-10
          • 2020-04-01
          相关资源
          最近更新 更多