Angular Templates: Null-Safe Navigation (?.)

What is Null-Safe Navigation (?.) in Angular Templates?

The null-safe navigation operator (?.) is used in Angular templates to safely access properties of objects that might be null or undefined.

It prevents the app from crashing with errors like:

“Cannot read property ‘name’ of undefined”


🎯 Why Do We Use ?. ?

If a variable is not yet loaded, for example from an API, you can still bind to it without errors.


📌 Basic Example

TS File


HTML Template


user?.name → Safe
user?.address?.city → Safe (won’t crash)
❌ Without ?., this would throw an error.

If the value is null → Angular simply displays nothing instead of breaking.


📌 Real Use Case: API Data Not Yet Loaded

TS

user: any; // Data will come later from API

 

HTML


Before data loads:

  • user is undefined

  • user?.profile?.name does NOT throw an error

After API loads:

  • It shows "Rahul"


📌 More Practical Examples

1️⃣ Accessing array items safely


2️⃣ Safe method calling


3️⃣ Safe access to form controls



⚠️ What Happens If Value Is Null?

Example:


If:

  • user = null → output is empty

  • address = null → output is empty

  • city = null → output is empty

Angular does NOT throw error.


✔️ Summary in One Line

👉 Use ?. when you want to access nested values safely without errors if something is null or undefined.

You may also like...