0

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>

2 Answers 2

2

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();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>

4 Comments

Works for me but if I don't want it to be in a JSON structure because I want to do CSS on it
you can use it <pre>{{item.subData | json}}</pre>
@DilipHirapara But I don't want the brackets and the array to appear
@DanielRazal use ngfor to loop on subdata and print the required values.Updated example for url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.