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?

1
  • It seems the option that is rendered doesn't have a name property. Try {{option | json}} instead, to see what option actually contains. Commented May 12, 2016 at 20:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I just added it to be sure. But the main issue is with model, so this doesn't really answer my question :(
I see. I guess there is more information necessary about how and where model gets it's value from .
Model either comes from outside via an input or if it's not defined then it will be set to the first option of options. But since that is not defined, it just becomes undefined.
Does this mean that there's no better thing to do than good old this.model = ... || {} in such case?
What about {{model?.name}}?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.