我有一个名为demo
的组件,其中显示了来自 API 的一些数据。
html
<div *ngFor="let user of users">
<p>Name: {{user?.name}}</p
<p>Phone: {{user?.addresses}}</p
</div>
ts
import { Component, Input } from '@angular/core';
import { User} from '../app-models';
@Component({
selector: 'wsd-demo',
templateUrl: './demo.component.html',
styleUrls: ['./demo.component.css'],
})
export class DemoComponent {
@Input()
public users: User;
}
app-models.ts(此文件中的声明界面(用户))
export interface User{
name: string;
addresses: IAddressElement[];
}
export interface IAddressElement {
type: string;
city: string;
countryOrRegion: string;
postalCode: string;
state: string;
}
Json
"name": "Jhon",
"addresses": [
{
"address": {
"type": "Home",
"city": "Loretto",
"countryOrRegion": "United States",
"postalCode": "00000",
"state": "Minnesota",
}
},
{
"address": {
"type": "Business",
"city": "Norwalk",
"countryOrRegion": "United States",
"postalCode": "1111",
"state": "Connecticut",
}
},
{
"address": {
"type": "Business",
"city": "Huntington",
"countryOrRegion": "United States",
"postalCode": "33333",
"state": "West Virginia",
}
}
],
我面临一个问题。在html中,name
显示正常。但是,同时显示地址(即地址)。
它显示为
[对象对象] [对象对象] 。
我想显示所有地址,我尝试使用 * ngFor ,但未获得确切结果。.:)
答案 0 :(得分:2)
您将按原样打印地址数组。您必须遍历它们并打印所需的内容。我不是Angular家伙。
<div *ngFor="let user of users">
<p>Name: {{user?.name}}</p>
<div *ngFor="let a of user?.addresses">
<p>State: {{a.address.state}}</p>
</div>
</div>