Stack Overflow [Angular] folks often ask:
- "Why doesn't my View show the data?"
- "I can see it in the request, and the data is returned but my component doesn't show it".
- "Why doesn't my data show up?"
Angular Render Events
Angular Rendering runs as soon as the component is displayed. This means any data that requires a Promise or Subscription misses the render event! Angular renders before the data has returned.
Solutions
-Use *ngIf to hide display until data arrives.
-Use ChangeDetector's detectChanges method after the data arrives. Like this:
<app-myComponent
// if *ngIf is missing,
// the view renders without
// waiting for person data
*ngIf='show'
[persons]='persons'>
</app-myComponent>
Solution
Don't show View until data is ready!
import {
Component,
OnInit,
ChangeDetectorRef}
from "@angular/core";
export class myComponent implements OnInit,
//default state is not to show at start.
show = false;
constructor(private cdf: ChangeDetectorRef);
ngOnInit(){
this.getData();
}
// a promise example
getData() {
this.getPersons().then((persons) => {
//sets the data sometime later
this.persons = persons;
// data is ready, show view!
this.show = true;
// tell Angular to re-render
this.cdf.detectChanges();
});
}
// a subscription example
getDataSubscription(){
this.getPersons.subscribe(result=>{
this.person = result;
// data is ready show view.
this.show = true;
this.cdf.detectChanges();
})
There are other ways but this is a good start.
Top comments (0)