I'm struggling with the async
pipe, I need to wait for the async data to finish loading before trying to render the view of the component.
I tried looking at this question where the elvis operator is mentioned:
Wait for Angular 2 to load/resolve model before rendering view/template
I tried it like {{model?['name']}}
but it doesn't seem to do anything because angular stills throws an error complaining about not being able to read name
of undefined
.
I initialize the model
on ngOnInit
but the data hasn't finished loading at this point (I think):
ngOnInit() {
// If no model is set and the select shouldn't be allowed empty, set the model to the first option
if (!this.model && !this.allowEmpty) {
this.model = this.options[0];
}
// If it should be allowed empty, set it to null which will add an empty class in the markup
else if (this.allowEmpty) {
this.model = null;
}
this.onModelChange.emit(this.model);
}
Then it tries to render this bit prematurely:
<div>
<ul>
<li>
<div>{{model?['name']}}</div>
<ul>
<li *ngFor="let option of options | async">{{option['name']}}</li>
</ul>
</li>
</ul>
</div>
So what would be the correct way of achieving this? Can I set something in the component class to allow async data to finish loading before rendering the view?