What is safe navigation operator in Angular?

Imgur

What is a safe navigation operator in Angular?

The Safe Navigation Operator is also known as the “Elvis Operator”. This operator is very useful to protect against null and undefined values in property paths.
Let’s suppose you have the following component and you want to display email in the UI

import { Component } from  "@angular/core";
 @Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export  class AppComponent {
user = null;
}

Whiout Safe navigation operator

<h1>{{user.email}}</h1>

If you run the application you will see the following error in console

ERROR

Error: Cannot read property 'email'  of  null

With safe navigation operator


<h1>{{user?.email}}</h1>

If you run the application will not see any error

Reactions

Post a Comment

0 Comments

Close Menu