首页 > 解决方案 > 使用动态对象数据在角度模板中显示对象数据

问题描述

我想以角度显示对象值到模板。但我的对象是动态的,所以我不知道它的键。我也尝试过管道键值,但这对我不起作用。我尝试了一种可能的解决方案,但无法完成它。我也将键值作为数组和对象获取,但无法在 ng 模板中解析我尝试过的内容-

data=[
{'a':12,'b':34,'d':32,'w':3}
{'a':2,'b':4,'d':3,'w':23}
{'a':24,'b':24,'d':13,'w':63}
]
key_name=['a','b','d','w']

在 html 文件中,我正在尝试使用 *ngFor

<ion-row class="data-table data-table-row" *ngFor="let data of tableData">
<ion-col> {{data}}</ion-col>
</ion-row>

*****我正在使用离子****,但是[object][object] 当我用它写键名时,数据正在显示数据

{{data.a}}

谢谢

标签: angularionic-frameworkionic2

解决方案


您可能必须使用两个*ngFor循环。尝试以下

tableData = [
  {'a':12,'b':34,'d':32,'w':3},
  {'a':2,'b':4,'d':3,'w':23},
  {'a':24,'b':24,'d':13,'w':63}
]
<ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
  <ng-container *ngFor="let item of data | keyvalue">    <!-- iterate the object in element of the array -->
    {{ item.key }} : {{ item.value }}
  </ng-container>
</ng-container>

或者,如果您不想迭代对象的每个属性,则可以使用json管道

<ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
  {{ data | json }}
</ng-container>

或者如果您仍然希望使用key_name数组来访问对象的属性,您可以尝试以下操作

<ng-container *ngFor="let data of tableData">    <!-- iterate the `tableData` array -->
  <ng-container *ngFor="let key of key_name">    <!-- iterate the `key_name` array -->
    {{ key }} : {{ data[key] }}
  </ng-container>
</ng-container>

推荐阅读