AngularJS 2.0 From The Beginning – Pipes – Day Eight (by Debasis Saha)

I am here to continue the discussion around AngularJS 2.0. Today, we will discuss about pipes in AngularJS 2. Also, if, you did not have a look at the previous articles of this series, go through the links, mentioned below.

In my previous article, I already discussed about the structural Directives in Angular 2.0. In that article, we discussed about some inbuilt structural Directives. Now, in this article, I will discuss about pipes, one of the new flavors of Angular 2 architectures.

In Angular 1.x, we are familiar with the term filter. Filters are a great way of returning a new collection of data or formatting the new or doing any existing changes or mutating. Filters are basically just functions, which take a single value or a collection of values as an input and return a new value or collection of the value, which is based on the logical responsibilities. In Angular 2.0, the pipes are the modernized version of the filters. Most of the inbuilt filters of Angular 1.x have been converted as pipes in Angular 2.0 with some new pipes. Pipes are accessed in our templates in the same way that filters were–with the "pipe" character |. The table given below shows a comparison of pipes or filters in both Angular 1.x and Angular 2.0.

Filter / Pipes Available Angular 1.x Angular 2.0
currency Yes Yes
date Yes Yes
uppercase Yes Yes
lowercase Yes Yes
Json Yes Yes
limitTo Yes Yes
Number Yes  
orderBy Yes  
Filter Yes  
async   Yes
decimal   Yes
percent   Yes

Thus, in this article, we will discuss how to use Angular 2.0 predefined pipes and also discuss how to create a custom pipe in Angular 2.0.

Basic Pipes

Most of the pipes provided by Angular 2.0 will be familiar to us, if we already worked in Angular 1.x. Actually pipes do not provide any new features in Angular 2.0. In Angular 2.0, we can use logic in the template. Also, we can execute or fire any function within the template to obtain its return value but actually pipe is a handsome way to handle this entire thing within the template. Also, it makes our code clean and structural. The pipe syntax starts with the actual input value followed by the pipe (|) symbol and then the pipe name. The parameters of that pipe can be sent separately by the colon (;) symbol. The order of execution of a pipe is right to left. Normally pipes works within our template and not in JavaScript code.

New pipes

The decimal and percent pipes are new in Angular 2.0. These take an argument that indicates the digit information, which should be used – that is how many integers and fraction digits; the number should be formatted with. The argument, which we pass for formatting follows this pattern: {minIntegerDigits}.{minFractionDigits} -{maxFractionDigits}.

Now, to show the inbuilt pipes in Angular 2.0, do the following.

 

Step 1 Create app.inbuildpipe.ts file and write down the code given below. 

  1. import { Component, OnInit } from ‘@angular/core’;  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: ‘inbuild-pipe’,  
  6.     templateUrl: ‘app.component.inbuildpipe.html’  
  7. })  
  8.   
  9. export class InBuildPipeComponent implements OnInit {  
  10.     private todayDate: Date;  
  11.     private amount: number;  
  12.     private message: string;  
  13.   
  14.     constructor() { }  
  15.   
  16.     ngOnInit(): void {  
  17.         this.todayDate = new Date();  
  18.         this.amount = 100;  
  19.         this.message = "Angular 2 is a Component Based Framework";  
  20.     }  
  21.       

Step 2 Now, add HTML file named app.component.inbuildpipe.html and add the code given below.

  1. <div>  
  2.     <h1>Demonstrate of Pipe in Angular 2.0</h1>  
  3.   
  4.     <h2>Date Format</h2>  
  5.     Full Date : {{todayDate}}<br />  
  6.     Short Date : {{todayDate | date:’shortDate’}}<br />  
  7.     Medium Date : {{todayDate | date:’mediumDate’}}<br />  
  8.     Full Date : {{todayDate | date:’fullDate’}}<br />  
  9.     Time : {{todayDate | date:’HH:MM’}}<br />  
  10.   
  11.     <h2>Number Format</h2>  
  12.     No Formatting : {{amount}}<br />  
  13.     2 Decimal Place : {{amount |number:’2.2-2′}}  
  14.   
  15.     <h2>Currency Format</h2>  
  16.     No Formatting : {{amount}}<br />  
  17.     USD Doller($) : {{amount |currency:’USD’:true}}<br />  
  18.     USD Doller : {{amount |currency:’USD’:false}}<br />  
  19.     INR() : {{amount |currency:’INR’:true}}<br />  
  20.     INR : {{amount |currency:’INR’:false}}<br />  
  21.   
  22.     <h2>String Message</h2>  
  23.     Actual Message : {{message}}<br />  
  24.     Lower Case : {{message | lowercase}}<br />  
  25.     Upper Case : {{message | uppercase}}<br />  
  26.   
  27.     <h2> Percentage Pipes</h2>  
  28.     2 Place Formatting : {{amount | percent :’.2′}}<br /><br />   
  29. </div> 

Step 3

Now, add another TypeScript file named app.module.ts and add the code given below.

  1. import { NgModule } from ‘@angular/core’;  
  2. import { BrowserModule } from ‘@angular/platform-browser’;  
  3. import { InBuildPipeComponent } from ‘./src/app.component.inbuildpipe’;  
  4.   
  5. @NgModule({  
  6.     imports: [BrowserModule],  
  7.     declarations: [InBuildPipeComponent],  
  8.     bootstrap: [InBuildPipeComponent]  
  9. })  
  10. export class AppModule { } 

Step 4

Now, add another ts file named main.ts and add the code given below.

  1. import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;  
  2.   
  3. import { AppModule } from ‘./app.module’;  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule); 

Step 5


Now, add another HTML file named index.html and add the code given below.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2</title>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <link rel="stylesheet" href="../styles.css">  
  8.     <!– Polyfill(s) for older browsers –>  
  9.     <script src="../node_modules/core-js/client/shim.min.js"></script>  
  10.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  11.     <script src="../node_modules/reflect-metadata/Reflect.js"></script>  
  12.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  13.     <script src="../systemjs.config.js"></script>  
  14.     <script>  
  15.         System.import(‘app’).catch(function (err) { console.error(err); });  
  16.     </script>  
  17. </head>  
  18. <body>  
  19.     <inbuild-pipe>Loading</inbuild-pipe>  
  20.       
  21. </body>  
  22. </html> 

Now, run the code and the output is shown below.

 

Custom

Now, we define a custom pipe in Angular 2.0. To configure custom pipes, we need to use pipe object. For this, we need to define custom pipe with @Pipe decorator and use it by adding a pipes property to the @View decorator with the pipe class name. We use the transform method to do any logic, which is necessary to convert the value being passed in as an input value. We can get a hold of the arguments array as the second parameter and pass in as many as we like from the template.

Now, for doing a custom proper case pipe, we need to add a type script file named app.component.propercase.ts and add the code given below.

  1. import { Pipe, PipeTransform } from "@angular/core"  
  2.   
  3. @Pipe({  
  4.     name: ‘propercase’  
  5. })  
  6. export class ProperCasePipe implements PipeTransform {  
  7.     transform(value: string, reverse: boolean): string {  
  8.         if (typeof (value) == ‘string’) {  
  9.             let intermediate = reverse == false ? value.toUpperCase() : value.toLowerCase();  
  10.             return (reverse == false ? intermediate[0].toLowerCase() :  
  11.                 intermediate[0].toUpperCase()) + intermediate.substr(1);  
  12.         }  
  13.         else {  
  14.             return value;  
  15.         }  
  16.     }  

Now, change the code of app.module.ts file, as shown below.

  1. import { NgModule } from ‘@angular/core’;  
  2. import { BrowserModule } from ‘@angular/platform-browser’;  
  3. import { InBuildPipeComponent } from ‘./src/app.component.inbuildpipe’;  
  4. import { ProperCasePipe } from ‘./src/app.component.propercasepipe’;  
  5.   
  6.   
  7. @NgModule({  
  8.     imports: [BrowserModule],  
  9.     declarations: [InBuildPipeComponent, ProperCasePipe],  
  10.     bootstrap: [InBuildPipeComponent]  
  11. })  
  12. export class AppModule { } 

Now, change the code of app.component.inbuildpipe.html file, as shown below.

  1. <div>  
  2.     <h1>Demonstrate of Pipe in Angular 2.0</h1>  
  3.   
  4.     <h2>Date Format</h2>  
  5.     Full Date : {{todayDate}}<br />  
  6.     Short Date : {{todayDate | date:’shortDate’}}<br />  
  7.     Medium Date : {{todayDate | date:’mediumDate’}}<br />  
  8.     Full Date : {{todayDate | date:’fullDate’}}<br />  
  9.     Time : {{todayDate | date:’HH:MM’}}<br />  
  10.   
  11.     <h2>Number Format</h2>  
  12.     No Formatting : {{amount}}<br />  
  13.     2 Decimal Place : {{amount |number:’2.2-2′}}  
  14.   
  15.     <h2>Currency Format</h2>  
  16.     No Formatting : {{amount}}<br />  
  17.     USD Doller($) : {{amount |currency:’USD’:true}}<br />  
  18.     USD Doller : {{amount |currency:’USD’:false}}<br />  
  19.     INR() : {{amount |currency:’INR’:true}}<br />  
  20.     INR : {{amount |currency:’INR’:false}}<br />  
  21.   
  22.     <h2>String Message</h2>  
  23.     Actual Message : {{message}}<br />  
  24.     Lower Case : {{message | lowercase}}<br />  
  25.     Upper Case : {{message | uppercase}}<br />  
  26.   
  27.     <h2> Percentage Pipes</h2>  
  28.     2 Place Formatting : {{amount | percent :’.2′}}<br /><br />   
  29.   
  30.     Custom Pipe or Proper Case : {{message | propercase}}  
  31. </div> 

Now, run the code.

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

TOP