matth3o matth3o - 10 months ago 53
Dart Question

dart angular2 - null error when rendering an object in template

I'd like to write in my template something like :


is initialized in my
, and my object seems to still be null when the page is rendered because I have the following error

NullError: method not found: 'myField' on null

If I only put in my template


I can see the value of

Is there a way to initialize my object before
? Is there another way to display my data ?

Thanks for your help.

Answer Source

You can use the safe-navigation operator


to prevent errors while the model is not yet fully initialized

Alternatively you can wrap the elements with *ngIf to prevent them being rendered when the model is not yet initialized

<span *ngIf="myObject != null">{{myObject.myField}}</span>

This way you can cover bigger blocks or the whole template with a single *ngIf instead of adding ? everywhere.