Angular Safe Navigation Operator

For those that are new to Angular there is an incredibly useful operator for use in templates. It is called the safe navigation operator and is noted with a question mark (?). Avoid the extra code of checking an object for null/undefined with the *ngIf directive in a template by using the safe navigation operator.

Using *ngIf

<div *ngIf="person">
{{person.name}}
</div>

Using safe navigation operator (?)

{{person?.name}}

If the person object in the example above is null/undefined then the rest of the expression is ignored and the name is not attempted to be resolved.

See the Template Syntax section of the Angular cheat sheet for other tips.





This entry was posted in Angular and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*