Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to use *ngFor with Parent Child components

What's the best way to loop through a child component multiple times, but with different data each time?

For example, within my 'sitelist' component (parent), I want to loop through my 'summary' component (child), as many times as it takes to get through the data. The 'summary' will just the data corresponding to each index in an array of objects I'm pulling from my service, 'sites.'

  1. What's the best way to display this data, considering this parent/child relationship?

  2. Which file (sitelist.component.ts or summary.component.ts) do I need to declare the data and grab it from the service?

For #1 what can I change to correctly loop through this data? Not sure I can pass data like that.

Sitelist.html (parent)

<div *ngFor="let site of sites">
  <app-summary></app-summary>
</div>

summary.html (child):

 <li>{{site.id}}</li>
 <li>{{site.name}}</li>
 <li>{{site.location}}</li>

For #2, Depending on the answer for #1, which file should I put my observable in to grab data from the service? (sitelist.component.ts or summary.component.ts)

ngOnInit() {
  let observable = this._dataService.getSites()
  observable.subscribe(data => {
      console.log("got info")
      console.log(data)
      this.sites = data
    })}
}

In my Service I have:

export class DataService {
    sites;
    constructor(private _http: HttpClient) { }
    getSites(){ 
      return this._http.get(`http://localhost:3000/sites.json`);
    }
}

Thanks!! let me know if I can clarify anything

like image 791
LaurenAH Avatar asked Sep 03 '25 03:09

LaurenAH


1 Answers

In your SummaryComponent, declare an @Input property that it's going to get from the SiteListComponent.

So the logic to get the sites list will go in your SiteListComponent class.

ngOnInit() {
  this._dataService.getSites()
    .subscribe(data => this.sites = data)
}

Pass the site(s) as an @Input property to SummaryComponent via property binding syntax like this:

<div *ngFor="let site of sites">
  <app-summary [site]="site"></app-summary>
</div>

And your SummaryComponent's TypeScript class should have a site variable decorated with the @Input decorator like this:

@Input() site;

Generally, the parent component(SiteListComponent) should be responsible to get the data from the service.

like image 197
SiddAjmera Avatar answered Sep 04 '25 18:09

SiddAjmera