我试图在ngFor
表中显示“ type”的值,但我正在获取类型为'object'的对象'[object Object]'。
NgFor仅支持绑定到可迭代对象,例如数组。**
json
[{
"id": 123,
"name": "Paul",
"cars":
{
"type": "toyota",
"year": "2013"
}
},
{
"id": 126,
"name": "Frank"
},
{
"id": 125,
"name": "Joy",
"cars":
{
"type": "bwm",
"year": "2000"
}
},
{
"id": 133,
"name": "Bob"
}]
html
//....
<tr *ngFor="let info of information;">
<td>{{info.name}}</td>
<td *ngFor="let info2 of info.cars;"> //I want to loop through and get the type value of cars
<td>{{info2.type}}</td>
</td>
<td><button type="button" (click)="showDetail()">View</button></td>
</tr>
//...
某些对象有汽车,如何获取表中的类型值?我需要帮助的另一个领域是,当单击“查看”按钮时,如何在输入字段上显示“类型”值(对于具有汽车属性的对象)。以下是我的.ts文件,需要在其中获取类型值:
comp.ts
//....
information = [];
carsType= {}; to hold type value for objects that has it
showDetail(data: any) {
this.formData.controls.name.setValue( data.name );
// how do I get cars "type" value for each object
}
答案 0 :(得分:2)
尝试这样:
<table border="1">
<tr *ngFor="let info of information;">
<td>{{info.name}}</td>
<td>{{info.cars?.type}}</td>
<td><button type="button" (click)="carType = info.cars?.type">View</button></td>
</tr>
</table>
<input type="text" [(ngModel)]="carType"/>
答案 1 :(得分:0)
尝试一下
<tr *ngFor="let info of information;">
<td>{{info.name}}</td>
<td>{{info?.cars?.type}}</td>
<td><button type="button" (click)="showDetail()">View</button></td>
</tr>