2

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.

1 Answer 1

2

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.

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

3 Comments

<span>{{myObject?.myField}}</span> works perfectly. Thanks!
In our project in same cases we usually add additional *ngIf="myObject == null" with some kind of spinner or loading lable as content, to indicate that component is not initialized yet. This approach can be easily converted to some custom guard control.
@StefanSvrkota Sure. Can you please delete yours. Dart is a nice language to build browser applications (and also server, and mobile, apps). Definitely worth a closer look ;-)

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.