Angular Pipe Operator (|) and Safe Navigation Operator (?.) Example
June 17, 2020
On this page we will provide Angular pipe operator and safe navigation operator example. These operators are Angular template expression operators. Pipe operator transforms an expression result into a desired output. Safe navigation operator avoids exception for null and undefined values in property paths. Pipe operator is denoted as (|) and they can be chained as well. Chaining pipe operator means we can use (|) more than one time. The output of one pipe operator will act as input for next pipe operator in pipe operator chaining. Safe navigation operator is denoted as (?.) and it is used while we are accessing a property from an object. In case our object is null or undefined then accessing properties from object will result into exception. If we access property from object using safe navigation operator then it will not throw exception. Pipe operator and safe navigation operator are used as follows.
1. Suppose
message
is a component property. Then pipe operator is used as below.
{{message | uppercase}}
2. Suppose
person
is a class instance and name
is a property of this class then safe navigation operator is used as below.
person?.name
Contents
Software Used
Find the technologies being used in our example.1. Angular 9.1.11
2. Node.js 12.5.0
3. NPM 6.9.0
Pipe Operator (|)
Pipe operator is an Angular template expression operator. Pipe operator transforms the expression result into a desired output. Pipe operator acts like a function that accepts an argument and returns transformed result. For example we want to display a message in uppercase or lowercase, a number as currency, component property as in JSON format etc. Syntax of Pipe operator is as follows.Expression | Transformation Type
Transformation type can be uppercase, lowercase, date, json etc.
Now find the typescript file and its HTML template.
company.ts
import {Person} from './person'; export class Company { constructor(public compname : string, public owner : Person) { } }
export class Person { constructor(public name : string, public dob : Date) { } }
import {Component} from '@angular/core'; import {Person} from './person'; import {Company} from './company'; @Component({ selector: 'pipe-operator-app', templateUrl: 'pipe.operator.component.html' }) export class PipeOperatorComponent{ message = 'Hello World!'; person = new Person('Mahesh', new Date(1980, 3, 12)); company = new Company('PQR', this.person); }
<h3>Pipe Operator </h3> <b>1. uppercase </b> <p>{{message | uppercase}} </p> <p>{{company.owner.name | uppercase}} </p> <b>2. lowercase </b> <p>{{message | lowercase}} </p> <b>3. date:'fullDate' </b> <p>{{person.dob | date:'fullDate'}} </p> <b>4. Pipe Chaining </b> <p>{{person.dob | date:'fullDate' | uppercase}} </p> <b> 5. json </b> <p>{{company | json}} </p>
1. Example for uppercase pipe:
Use Pipe operator (|) with uppercase pipe.
{{message | uppercase}}
HELLO WORLD!
{{message | lowercase}}
hello world!
{{person.dob | date:'fullDate'}}
Saturday, April 12, 1980
4. Example for pipe operator chaining:
We can use pipe operator more than one time to get a desired output that is called pipe operator chaining. In pipe operator chaining, the output of one pipe operator will be the input for next pipe operator and so on.
{{person.dob | date:'fullDate' | uppercase}}
SATURDAY, APRIL 12, 1980
person.dob
first date pipe will applied and then on that output uppercase pipe will be applied.
5. Example for json pipe :
Using json pipe we can display our component property into JSON format. Find the code snippet.
{{company | json}}
company
is the instance of Company
class. Output will be as follows.
{ "compname": "PQR", "owner": { "name": "Mahesh", "dob": "1980-04-11T18:30:00.000Z" } }
Safe Navigation Operator (?.)
Safe navigation operator ( ?. ) is an Angular template expression operator. Safe navigation operator avoids exception for null and undefined values in property paths. While accessing properties from object it may throw exception if object is null or undefined. For safer side we can use safe navigation operator to access property from object and hence it will not throw exception for the scenario that object is null or undefined. If we have an objectperson
with the properties name
then using safe navigation operator we will access object property as follows.
person?.name
Now find the typescript file and its HTML template used in our example.
safe.navigation.operator.component.ts
import {Component} from '@angular/core'; import {Person} from './person'; import {Company} from './company'; @Component({ selector: 'safe-nav-operator-app', templateUrl: 'safe.navigation.operator.component.html' }) export class SafeNavigationOperatorComponent { personone : Person; persontwo = new Person('Ramesh', new Date(1990, 3, 10)); companyone = null; companytwo = new Company('ABC', this.personone); companythree = new Company('XYZ', this.persontwo); }
<h3>Safe Navigation Operator</h3> <!--personone is undefined, It will throw error --> <!--p>{{personone.name}} </p> <p>{{personone.dob}} </p--> <b>1. </b> <p>{{personone?.name}} </p> <p>{{personone?.dob}} </p> <b>2. </b> <p *ngIf="personone">{{personone?.name}} </p> <p *ngIf="personone">{{personone?.dob}} </p> <br/> <b>3. </b> <p>{{persontwo?.name}} </p> <p>{{persontwo?.dob | date:'fullDate'}} </p> <!--companyone is null, It will throw error --> <!--p>{{companyone.compname}} </p> <p>{{companyone.owner.name}} </p> <p>{{companyone.owner.dob}} </p--> <b>4. </b> <p>{{companyone?.compname}} </p> <p>{{companyone?.owner?.name}} </p> <p>{{companyone?.owner?.dob}} </p> <b>5. </b> <p>{{companytwo?.compname}} </p> <p>{{companytwo?.owner?.name}} </p> <p>{{companytwo?.owner?.dob}} </p> <b>6. </b> <p>{{companythree?.compname}} </p> <p>{{companythree?.owner?.name}} </p> <p>{{companythree?.owner?.dob}} </p>
<p>{{personone.name}} </p> <p>{{personone.dob}} </p>
personone
is undefined. The code personone.name
and personone.dob
will throw exception as follows.
EXCEPTION: Error in app/safe.navigation.operator.component.html:3:3 caused by: self.context.personone is undefined core.umd.js:3004:13 ORIGINAL EXCEPTION: self.context.personone is undefined
{{personone?.name}} {{personone?.dob}}
2. To avoid "undefined" and "null" exception we can also use
NgIf
<p *ngIf="personone">{{personone?.name}} </p> <p *ngIf="personone">{{personone?.dob}} </p>
personone
is undefined, so ngIf
block will not execute and hence <p> tag will not be created.
3. It is safer side to use safe navigation operator for component property even if they have been initialized.
{{persontwo?.name}} {{persontwo?.dob | date:'fullDate'}}
companyone
property is null. So when we access following code of line
{{companyone.compname}} {{companyone.owner.name}} {{companyone.owner.dob}}
EXCEPTION: Error in app/safe.navigation.operator.component.html:20:3 caused by: self.context.companyone is null core.umd.js:3004:13 ORIGINAL EXCEPTION: self.context.companyone is null
{{companyone?.compname}} {{companyone?.owner?.name}} {{companyone?.owner?.dob}}
5. The component property
companytwo
has been initialized with an undefined property personone
, so accessing companytwo?.owner.name
will throw exception. This is because owner
has been assigned with the value of personone
that is undefined. Use safe navigation operator in property path with owner
property.
{{companytwo?.compname}} {{companytwo?.owner?.name}} {{companytwo?.owner?.dob}}
6.
companythree
has been initialized with proper values that will not let it throw exception. Still we should use safe navigation operator to avoid exception in case companythree
property is re-initialized somewhere else in component code.
{{companythree?.compname}} {{companythree?.owner?.name}} {{companythree?.owner?.dob}}
Create Component and Module
app.component.ts
import {Component} from '@angular/core'; @Component({ selector: 'app-root', template: ` <pipe-operator-app> </pipe-operator-app> <safe-nav-operator-app></safe-nav-operator-app> ` }) export class AppComponent { }
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {AppComponent} from './app.component'; import {PipeOperatorComponent} from './pipe.operator.component'; import {SafeNavigationOperatorComponent} from './safe.navigation.operator.component'; @NgModule({ imports: [BrowserModule], declarations: [AppComponent, PipeOperatorComponent, SafeNavigationOperatorComponent], bootstrap: [AppComponent] }) export class AppModule { }
Run Application
To run the application, find the steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.
