0

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?

Community
  • 1
  • 1
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • It seems the `option` that is rendered doesn't have a `name` property. Try `{{option | json}}` instead, to see what `option` actually contains. – Günter Zöchbauer May 12 '16 at 20:03

1 Answers1

0

You can't use ? with []

If you use

*ngFor="let option of options | async">

then option in

{{option.name}}

always has a value because no <li ... is rendered when options hasn't yet emitted data.

{{option?.name}}

would be a valid use and do what you seemed to intend to do but as mentioned above, it shouldn't be necessary.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567