Skip to main content

How does the safe navigation operator (?.) work in a template?

In Angular, the safe navigation operator (?.) is used in a template to safely access properties of objects that may be null or undefined, to avoid runtime errors.

Main points

  1. Syntax:
html
<p>{{ user?.name }}</p>
  • If user is not null and not undefined, user.name is displayed.
  • If user equals null or undefined, Angular simply outputs an empty string instead of an error.
  1. Can be used to call methods:
html
<p>{{ user?.getFullName() }}</p>
  • The method is called only if user exists.
  1. Applied with a chain of objects:
html
<p>{{ user?.address?.city }}</p>
  • Safely checks each level of nesting, preventing errors like "Cannot read property 'city' of undefined".

In other words, ?. is a guard for the template against errors when accessing potentially missing objects or properties.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.