Angular Templates: Null-Safe Navigation (?.)
Safely read optional values with ?.
and provide defaults with ??
.
What is Null-Safe Navigation (?.)?
?.
reads values that might be missing without throwing errors.- If any segment is
null
orundefined
, the result isundefined
. - Improves safety for deep property paths in templates.
When to use Null-Safe Navigation
- Async or optional data where properties may be absent.
- Use
?.
(and optional chaining in code) over verbose checks. - Combine with
??
to provide default values.
Example
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `
<button (click)="toggle()">Toggle user</button>
<p>Email: {{ user?.profile?.email || '(none)' }}</p>
`
})
export class App {
user: { profile?: { email?: string } } | undefined = undefined;
toggle() {
this.user = this.user ? undefined : { profile: { email: 'a@example.com' } };
}
}
bootstrapApplication(App);
<app-root></app-root>
Example explained
- Optional chaining (?.):
user?.profile?.email
reads email only if user and profile are defined; otherwise the whole expression isundefined
(no error). - Fallback:
|| '(none)'
shows a placeholder when the expression is falsy; prefer??
when you want to treat0
or empty strings as valid. - Toggle: Clicking “Toggle user” alternates
user
betweenundefined
and an object to demonstrate safe access.
Nullish coalescing (??): Use a ?? b
over a || b
when you want to keep valid falsy values like 0
or ''
.