I want to populate data in my select control which is placed in the header child component, but data comes from the API, but it does not display.
ngOnInit() {
this._assingedSiteService.getAssignedSitesForLogInUser().subscribe(
(res) => {
this.sites = res;
console.log(this.sites);
},
(error) => {
console.log(error);
}
);
}
<li class="nav-item">
<select class="form-control">
<option *ngFor="let site of sites">
{{site.siteName | json}}
</option>
</select>
</li>
You need to wait for the received data before rendering the page. You can do two things:
Use a boolean and ngIf
directive so:
loadingData = true;
ngOnInit() {
this._assingedSiteService.getAssignedSitesForLogInUser().subscribe((res) => {
this.sites = res;
console.log(this.sites);
this.loadingData = false;
}, (error) => {
console.log(error);
}
);
}
Template
<select class="form-control" *ngIf="!loadingData">
<option *ngFor="let site of sites">
{{site.siteName | json}}
</option>
</select>
Which I prefer, if you have no logic inside your subscription, use async
pipe inside your template:
sites$: Observable<Site>;
ngOnInit() {
this.sites$ = this._assingedSiteService.getAssignedSitesForLogInUser();
}
Template:
<select class="form-control">
<option *ngFor="let site of sites$ | async">
{{site.siteName | json}}
</option>
</select>