matth3o matth3o - 2 months ago 13
Dart Question

dart angular2 - null error when rendering an object in template

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

<span>{{myObject.myField}}</span>


However
myObject
is initialized in my
ngOnInit
, 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

<span>{{myObject}}</span>


I can see the value of
myObject
.

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

Thanks for your help.

Answer

You can use the safe-navigation operator

<span>{{myObject?.myField}}</span>

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.