user2959870 user2959870 - 1 year ago 86
TypeScript Question

How to not get an error if a data filed is not present in Angular 2

I'm building an application with Angular 2. I am also using a database.
I get an error if I type this line of code:

<span class="col-sm-6">{{}}</span>

The error is:

"Cannot read property 'date' of null"

This is actually a correct error, because i don't have a property of date yet. I know for sure there will be a date property in the future.

I want Angular 2 not to throw an error, just display nothing on the page.

Answer Source

You can use safe navigation operator (?). It protects template from null/undefined values:

<span class="col-sm-6">{{workorder?.timeWindowAppointment?.date}}</span>

Read more about it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download