When I try to display my subData in Angular I get [object Object]: enter image description here
I have a model that can contain an array of sites:
public class Site
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public Site[]? SubData { get; set; }
}
JSON Example:
{
"id": 1,
"name": "Google",
"url": "http://www.google.com",
"subData": [
{
"id": 2,
"name": "Walla",
"url": "http://www.walla.co.il"
}
]
},
components.ts:
export class AppComponent implements OnInit{
sites: Site[] = [];
constructor(private siteService:SiteService) { }
ngOnInit(): void {
this.GetSites();
}
GetSites() {
this.siteService.GetSites()
.subscribe((sites) => {
JSON.stringify(this.sites = sites);
});
}
}
html:
<div *ngFor="let item of sites;">
<div>Id: {{item.id}}</div>
<div>Site Name: {{item.name}}</div>
<div>Site Url: <a href="{{item.url}}">{{item.url}}</a></div>
<div>{{item.subData}}</div>
</div>
CodePudding user response:
You make it even cleaner with async pipe:
<div *ngFor="let item of sites$ | async as site;"> // use async pipe here
<div>Id: {{site.id}}</div>
<div>Site Name: {{site.name}}</div>
<div>Site Url: <a href="{{site.url}}">{{site.url}}</a></div>
// use ngfor for subdata
<div *ngFor="let subSite of site?.subData"> // use ? for safety
<div> {{subSite?.url}}</div>
</div>
</div>
export class AppComponent implements OnInit{
sites$: Observable<Site[]>;
constructor(private siteService:SiteService) { }
ngOnInit(): void {
this.GetSites();
}
GetSites() {
this.sites$ = this.siteService.GetSites();
}
}
CodePudding user response:
use json pipe something like
<div>{{item.subData | json}}</div>
Update as per comment to display as html element use ngFor loop
<div *ngFor="let i of item.subData">
<div> {{i.url}}</div>
</div>