Introduction To Safe Navigation Operator In Angular 2

Introduction

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. This operator allows us to navigate an object path in situations when we are not aware whether a path exists or not. It returns value of the object path if it exists, else it returns the null value. It is very useful to prevent null-reference exceptions.

Syntax

Object?.path

Example

Let's have an example. In the first case, I am trying to retrieve the data from the object path "data.firstName" using interpolation. Here, I am not defining the data so Angular parsing throws runtime null-reference exceptions. Here, our application crashes when the data is null.

example.html

  1. <div> Hi, This Text will generate error!!! {{data.firstName}} </div>  
Output

Syntax

In the following example, I am using the Safe Navigation Operator. So, it is protecting against the null exception.

example.html
  1. <div> Hi, This Text will not generating error Console!!! {{data?.firstName}} </div>  
Output

Syntax

Alternative of Safe Navigation Operator

 

  1. The same behavior can be achieved using *ngIf Directive. In the following example, I have hidden the text when the "data" is null.

    example.html
    1. <div *ngIf="data"> Hi, This Text will not generating error Console!!! {{data.firstName.text}} - *ngIf Example </div>  
    Output

    Syntax

  2. The second alternative is to use "&& operator". Here, we first check for "data". When it is not null, then Angular will populate the data.firstname, else null.

    example.html
    1. <div> Hi, This Text will not generating error Console!!! {{ data && data.firstName.text}} </div>  
    Output is similar to what we got from Safe Navigation Operator.

    These approaches are good but they become very bulky when the property path is long. For example, if I want to protect against a null for long property path, such as p.q.r.s., in this case, Angular Safe Navigation Operator (?.) is a more useful and convenient way to protect against null reference exception. It works perfectly with long property paths- such as p?.q?.r?.s.

Conclusion

The Safe Navigation Operator is very useful to protect against null and undefined values in the property paths. In this article, we also learned the alternatives of this operator and the advantages of this operator over alternatives.

Note - Here, I have not included the dependency of the example project. To run project, you need to perform "npm install" command to download the project dependency.