0
0
Angularframework~5 mins

Safe navigation operator for null in Angular

Choose your learning style9 modes available
Introduction

The safe navigation operator helps you access properties safely when some data might be missing or null. It prevents errors by stopping the code from breaking if a value is null or undefined.

When displaying user profile details that might not be loaded yet.
When accessing nested object properties that may not exist.
When working with data from APIs that can return incomplete information.
When binding values in templates where some parts can be null.
When you want to avoid app crashes caused by null or undefined values.
Syntax
Angular
{{ object?.property }}
The ?. operator checks if object is not null or undefined before accessing property.
If object is null or undefined, it returns null instead of throwing an error.
Examples
Displays the user's name only if user exists. Otherwise, shows nothing.
Angular
{{ user?.name }}
Accesses the customer's address safely, even if order or customer is null.
Angular
{{ order?.customer?.address }}
Shows the price only if product, details, and price exist.
Angular
<div *ngIf="product?.details?.price">Price: {{ product?.details?.price }}</div>
Sample Program

This component tries to show the user's name and city. The city is inside address, which is missing. Using the safe navigation operator ?. prevents errors and shows nothing for city.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-safe-nav',
  template: `
    <h2>User Info</h2>
    <p>Name: {{ user?.name }}</p>
    <p>City: {{ user?.address?.city }}</p>
  `
})
export class SafeNavComponent {
  user = {
    name: 'Alice',
    // address is missing
  };
}
OutputSuccess
Important Notes

The safe navigation operator works in Angular templates and in TypeScript code.

It helps keep your app running smoothly even when data is incomplete or loading.

Summary

The safe navigation operator ?. prevents errors when accessing null or undefined values.

Use it in templates to safely access nested properties.

It improves app stability and user experience by avoiding crashes.