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
- Syntax:
html
<p>{{ user?.name }}</p>- If
useris notnulland notundefined,user.nameis displayed. - If
userequalsnullorundefined, Angular simply outputs an empty string instead of an error.
- Can be used to call methods:
html
<p>{{ user?.getFullName() }}</p>- The method is called only if
userexists.
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.