Home  >  Angular

Angular 2 Pipe Operator (|) and Safe Navigation Operator (?.) Example

By Arvind Rai, December 12, 2016
On this page we will provide angular 2 pipe operator and safe navigation operator example. These operators are angular 2 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 
Now here on this page we will provide complete example of pipe operator and safe navigation operator step by step using typescript.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

Pipe Operator (|)

Pipe operator is an angular 2 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) {
	}
} 
person.ts
export class Person {
	constructor(public name : string, public dob : Date) {
	}
} 
pipe.operator.component.ts
import {Component} from '@angular/core';
import {Person} from './person';
import {Company} from './company';
@Component({
    selector: 'pipe-operator-app',
    templateUrl: 'app/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);
}  
pipe.operator.component.html
<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}}   
Output will be as follows.
HELLO WORLD!  
2. Example for lowercase pipe:
{{message | lowercase}}  
Output will be as follows.
hello world!  
3. Example for date pipe with fullDate format:
{{person.dob | date:'fullDate'}}  
Find the output.
Saturday, April 12, 1980  
To learn more about date pipe find the link Angular 2 Date Pipe Example

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}}  
Find the output.
SATURDAY, APRIL 12, 1980  
Here on the output of 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}}  
Here 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 2 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 object person 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: 'app/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);
}  
safe.navigation.operator.component.html
<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> 
Find the code snippet.
<p>{{personone.name}} </p>
<p>{{personone.dob}} </p>  
In our component 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  
1. To avoid exception, we can use safe navigation operator (?.) as follows.
{{personone?.name}} 
{{personone?.dob}}  
Now the above code will not throw exception.

2. To avoid "undefined" and "null" exception we can also use NgIf
<p *ngIf="personone">{{personone?.name}} </p>
<p *ngIf="personone">{{personone?.dob}} </p>  
As 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'}}  
In our component companyone property is null. So when we access following code of line
{{companyone.compname}} 
{{companyone.owner.name}} 
{{companyone.owner.dob}}  
It will throw exception as follows.
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  
4. Now use safe navigation operator.
{{companyone?.compname}}
{{companyone?.owner?.name}} 
{{companyone?.owner?.dob}}  
The above code snippet will not throw exception.

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}}  
Now the above code snippet will not throw exception.

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, Module, Main and index.html using TypeScript


app.component.ts
import {Component} from '@angular/core';
@Component({
    selector: 'operator-app',
    template: `
	        <pipe-operator-app> </pipe-operator-app>
		<safe-nav-operator-app></safe-nav-operator-app>
	      `
})
export class AppComponent { }  
module.ts
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 { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  
index.html
<html>
  <head>
    <title>Angular 2 Demo</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('myApp').catch(function(err){ console.error(err); });
    </script>
  </head>
  <body>
    <operator-app>Please Wait...</operator-app>
  </body>
</html> 

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 Pipe Operator (|) and  Safe Navigation Operator (?.) Example

References

Angular 2 pipe operator (|)
Angular 2 safe navigation operator (?.) and null property paths

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us