How to avoid error if don’t check if {{object.field}} exists with Angular?

Sometimes, we want to avoid error if don’t check if {{object.field}} exists with Angular.

In this article, we’ll look at how to avoid error if don’t check if {{object.field}} exists with Angular.

How to avoid error if don’t check if {{object.field}} exists with Angular?

To avoid error if don’t check if {{object.field}} exists with Angular, we can use the safe navigation operator in our template.

For instance, we write

{{ category?.name }}

to add the safe navigation operator with ?..

Then we don’t have to check if category is defined before we try to get its name property.

If the object is an array, then we check if it’s defined with

{{ records && records[0] }}

where records is an array.

We can also use the safe navigation operator with the async pipe with

{{ (chapters | async)?.length }}

where chapter is a promise or observable.

The safe navigation operator works with ngModel.

To use it, we write

<input
  [ngModel]="details?.firstname"
  (ngModelChange)="details.firstname = $event"
/>

to bind to details?.firstname with ngModel and ngModelChange.

Conclusion

To avoid error if don’t check if {{object.field}} exists with Angular, we can use the safe navigation operator in our template.