This article covers following topics in details:
- Purpose of having pipes in Angular.
- Built in Pipes and its usage.
- How to create custom Pipes
Purpose of having pipes in Angular.
Pipes are used to format your data based on the requirement. Pipes donate from symbol “|” and you can use it inside the HTML template where you display the data with interpolation.
Example if you want to format amount bases on some currency type you can use below expression.
{{ amount | currency:'EUR' }}
Pipes is simply a function which accept an input values such as integers, strings, arrays, and date and returns the transform value and display the same in the browser.
Built in Pipes and its usage.
There are several built in pipes in Angular.
- Uppercase pipe
- Lowercase pipe
- Date pipe
- Currency pipe
- Percent pipe
- Decimal pipe
- Slice pipe
After setting up the environment and creating the example app we will try out each default pipe provided by Angular framework.
Angular Related Articles:
Setting up the environment.
Please refer Setting up the environment.
I will create a new project AngularPipes. After setting up your environment please run the below command in your command prompt.
ng new angular-pipes
This will create the new project with all the necessary default libraries and files.
Now go inside the angular-pipe folder and run ng serve to up and run your application with default settings. Type http://localhost:4200/ in your browser to see the app is running.
Go to app.component.ts and type below codes. Here I have defined set of variables and assigned values to use in template file to show the usage of pipes.
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { title = 'angular-pipes'; todayNumber: number = Date.now(); todayDate : Date = new Date(); todayString : string = new Date().toDateString(); todayISOString : string = new Date().toISOString(); amount = 1000; floatValues = 2.5; number1 = 13.456789; week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; arrayToTranform = [1000,1500,5000];}
Now let us see how we can use each default pipes. Type below codes in app.component.html file and see the output in a browser.
1. Uppercase Pipe
<h1>datepipe for milisecond value: {{todayNumber}}</h1> <h2> {{todayNumber | date}} </h2>
<h1>datepipe for date Object: {{todayDate}}</h1> <h2> {{todayDate | date}} </h2>
<h1>datepipe for date String: {{todayString}}</h1> <h2> {{todayString | date}} </h2> <h1>datepipe for ISO date String: {{todayISOString}}</h1> <h2> {{todayISOString | date}} </h2>
All types of datetime values displays the date in ‘MMM d, yyyy’ format which is default Angular date format ‘mediumDate’
To change the datetime format in angular we must pass date time format parameter to the angular pipe.
There are 12 predefined date types in Angular. We must pass first parameter “format” as quoted string with the predefined date format names listed below.
Example:
{{todayDate | date :'short'}}
Below are the 12 formats that you can pass along with the date pipe to show date values in various ways.
short
medium
long
full
shortDate
mediumDate
longDate
fullDate
shortTime
mediumTime
longTime
fullTime
4. Currency pipe
Below example will show how you can use angular currency pipe based on locale. If you do not pass the locale default value taken as USD.
<h1>Amount {{amount}} in USD format</h1> <h2> {{amount | currency}} </h2>
<h1>Amount {{amount}} in Japanese yen format</h1>
<h2> {{ amount | currency:'JPY' }} </h2>
5. Percent pipe
Percent pipe is used to format the number based on the percentage. As an example, let us see how below code is working.
<h1>Amount {{floatValues}} as a percentage</h1> <h2> {{floatValues | percent}} </h2>
<h1>Amount {{floatValues}} as a percentage</h1> <h2> {{floatValues | percent:'2.2-5'}} </h2>
{{floatValues | percent:'2.2-5'}}
Above syntax means you are going to represent number in a format as below.
minIntegerDigits = 2
minFractionDigits = 2
maxFractionDigits = 5
Default format for percent pipe is as below.
minIntegerDigits = 1
minFractionDigits = 0
maxFractionDigits = 3
6. Decimal pipe
DecimalPipe is used to format a number as decimal number. It uses number keyword with pipe operator.
<h1>Amount {{number1}} as a decimal value</h1> <h2> {{number1 | number}} </h2>
<h1>Amount {{number1}} as a decimal value</h1> <h2> {{number1 | number:'2.2-5'}} </h2>
{{number1 | number:'2.2-5'}}
Above syntax means you are going to represent number in a format as below.
minIntegerDigits = 2
minFractionDigits = 2
maxFractionDigits = 5
Default format for decimal pipe is as below.
minIntegerDigits = 1
minFractionDigits = 0
maxFractionDigits = 3
7. Slice pipe
Slice pipe is used to slice your array when you are displaying data. For an example in my app.component.ts file has an array named week. If I wanted to show only first three day of the week, I can use slice pipe.
week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
<h1>All days in a week</h1> <div *ngFor="let day of week"> {{day}} </div>
<h1>First 3 day in a week</h1> <div *ngFor="let day of week|slice:0:3"> {{day}} </div>
Creating a custom Pipe
So far, we have studied different kind of angular built-in pipes that we can used to format our data based on the requirement. Now we will look in to how you can write your own custom pipe. If the built-in pipes in angular does not fit for your requirement you can create your own pipe.
As an example, let us say I wanted transform integer numbers as below.
1000 -> 1k
1500 -> 1.5k
5000 -> 5k
Let us see how you can achieve this using your own custom pipe.
In my project folder I have create the new folder called pipe and I created the new .ts file named as formatNumber.
Below code represent my code in the formatNumber.ts file. To create Pipe you must import module Pipe from angular/core library.
import { Pipe } from '@angular/core';
@Pipe({ name: 'format-number'})export class FormatNumberPipe{ }
After creating a pipe class you must declare it inside the app.module.ts file as below to use this new pipe in your application.
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { FormatNumberPipe } from './pipe/formatNumber';
@NgModule({ declarations: [ AppComponent, FormatNumberPipe ], imports: [ BrowserModule, AppRoutingModule, ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
To implement the custom pipe functionality you need to use @Pipe decorator and must implement the interface “PipeTransform” and override the method “transform()” as below.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'formatNumber'})export class FormatNumberPipe implements PipeTransform{ transform(n: number) : string { return (n /1000)+"K"; }}
In above code I have read the input number “n” and I have implemented the logic to return the output as per my requirement.
In my app.component.ts file has below array. Let us see what would be the out put after I apply my custom pipe to the values in the array.
arrayToTranform = [1000,1500,5000];
<h1>Before applying custom pipe</h1> <div *ngFor = "let number of arrayToTranform "> {{number}} </div>
<h1>After applying custom pipe</h1> <div *ngFor = "let number of arrayToTranform"> {{number | formatNumber}} </div>
Congratulations! You have successfully applied your custom pipes to format the numbers to match with your requirement. Once you go through this article you should be able to understand Angular built-in pipes and what is the purpose of having them and how you are going to use them. Secondly you will be able to create your own pipe simply to transform the data based on the requirement.
We will meet in another useful article like this sooner. GOOD LUCK 😊
Comments
Post a Comment