• Skip to content
  • Skip to primary sidebar
  • Home
  • Angular
  • ASP.NET Core
  • Entity Framework
    • Entity Framework 6
    • Entity Framework Core
  • Crystal Reports
  • C#
  • ASP.NET
  • About Us
    • Privacy Policy
    • Contact Us

TekTutorialsHub

Free Online Tutorials

Angular 2 Pipes

November 26, 2016 by TekTutorialsHub 3 Comments

ngStyle Directive
Angular 2 Custom Pipes
 

Angular 2 Pipes helps us to format or transform data to display in our template. They are similar to Filters in AngularJS. In this Tutorial, we are going to look at what is pipes are & how to use them. We will see how to pass arguments to the pipe and how to chain pipes. We are also going to look at the few list of angular 2 built-in pipes like currency pipe, date pipe, number pipe, percent pipe, decimal pipe, & slice pipe.

In this article

  • Angular 2 Pipes
    • Syntax of Pipe
    • Using the Pipes
    • Passing arguments
    • Chaining Pipes
  • The Angular 2 Built-in pipes
    • DatePipe
      • Example of Datepipe
    • UpperCasePipe & LowerCasePipe
    • SlicePipe
      • Syntax
      • Example
    • DecimalPipe / NumberPipe
      • Syntax
      • Example
    • PercentePipe
      • Example code
    • CurrencyPipe
      • Example

Angular 2 Pipes

There are many circumstances where we may have to change the appearance of the data before presenting it the user. The most common examples are dates. That is where Angular 2 Pipes comes handy. They take the data as input and transforms that data to get the desired output.

Syntax of Pipe

1
2
3
 
Expression | pipeOperator[:pipeArguments]
 

Where

Expression : is the expression, which you want to transform

| : is the Pipe Character

pipeOperator : name of the Pipe

pipeArguments: arguments to the Pipe

Using the Pipes

In this example let use Angular 2 built in date pipe to transform the date

Component class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
@Component({
    selector: 'app-root',
    templateUrl: `<p> Unformatted date : {{toDate }} </p>
                  <p> Formatted date : {{toDate | date}} </p>`
})
export class AppComponent
{
    title: string = 'pipe Example' ;
    toDate: Date = new Date();
}
 

In the above example, we are taking current date and transforming it into the easily readable format using the date pipe. We have included the unformatted date format for comparison. The output is as shown below

Example of Angular 2 Pipes
Example of Angular 2 Pipes

Passing arguments

We can also pass optional arguments to the pipe. The arguments are added to the pipe using a colon (:) sign followed by the value of the argument. If there are multiple arguments separate each of them with the colon (:). For example date pipe accepts one optional argument called “format”. The “medium” is one of the valid value of the format argument, which displays the date in “yMMMdjms” format. The example code is as shown below.

1
2
3
 
{{toDate | date:'medium'}}
 

The parameter ‘medium’ displays the date as Nov 22, 2016, 10:04:10 PM

Chaining Pipes

Pipes can be chained together to make use of multiple pipes in one expression. For example in the following code, the toDate is passed to the Date Pipe. The output of Date pipe is then passed to the uppercase pipe.

1
2
3
 
toDate | date | uppercase
 

The Angular 2 Built-in pipes

The Angular 2 has several built-in pipes, which you can use in your application. You can read about them from this link

Some of the important pipes are Date Pipe, Uppercase Pipe, LowercasePipe, Number Pipe/Decimal Pipe, Currency Pipe, and Percent Pipe etc

DatePipe

The Date pipe formats the date according to locale rules. The syntax of the date pipe is as shown below

1
2
3
 
date_expression | date[:format]
 

Where

date_expression is a date object or a number

date is the name of the pipe

format is the date and time format string which indicates the format in which date/time components are displayed.

Some of the common format strings are

ComponentformatExample
Yeary2016
Yearyy16
MonthM9
MonthM99
MonthMMMNov
MonthMMMMNovember
Dayd9
Daydd09
hourj9
hourjj09
hourh9 AM
hourhh09 AM
hour24H13
hour24HH13
minutem9
minutemm09
seconds9
secondss99
Time zonezPacific Standard time
Time zoneZGMT-8:00
Time zoneaPM
eraGAD
eraGGGGAnno Domini

Format argument also supports some predefined commonly used formats

Format NameEquivalent Format strngExample
(for en-US)
mediumyMMMdjmsSep 3, 2010, 12:05:08 PM
shortyMdjm9/3/2010, 12:05 PM
fullDateyMMMMEEEEdFriday, September 3, 2010
longDateyMMMMdSeptember 3, 2010
mediumDateyMMMdSep 3, 2010
shortDateyMd9/3/2010
mediumTimejms12:05:08 PM
shortTimejm12:05 PM

You can read about the complete list from link

Example of Datepipe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template:`<p>medium : {{toDate | date:'medium'}} </p>
              <p>short : {{toDate | date:'short'}} </p>
              <p>fullDate : {{toDate | date:'fullDate'}} </p>
              <p>longDate : {{toDate | date:'longDate'}} </p>
              <p>mediumDate : {{toDate | date:'mediumDate'}} </p>
              <p>shortDate : {{toDate | date:'shortDate'}} </p>
              <p>mediumTime : {{toDate | date:'mediumTime'}} </p>
              <p>dd-MM-y : {{toDate | date:'dd-MM-y'}} </p>
              <p>dd-MM-yy HH:mm : {{toDate | date:'dd-MM-yy HH:mm'}} </p>`
})
export class AppComponent
{
    title: string = 'Angular 2 pipes Example' ;
    toDate: Date = new Date();
}
 

UpperCasePipe & LowerCasePipe

As the name suggests, these pipes transform the string to Uppercase or lowercase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
@Component({
    selector: 'app-root',
    template:`<p>Unformatted :{{msg}} </p>
              <p>Uppercase :{{msg | uppercase}} </p>
              <p>Lowercase :{{msg | lowercase}} </p>`
})
export class AppComponent
{
    title: string = 'Angular 2 pipes Example' ;
    msg: string= 'Welcome to Angular 2';
}
 

Read more about uppercasepipe & lowercasepipe

SlicePipe

Creates a new List or String containing a subset (slice) of the string or array. This Pipe uses the JavaScript API Array.prototype.slice() and String.prototype.slice().

Syntax

1
2
3
 
array_or_string_expression | slice:start[:end]
 

Where

array_or_string_expression is the string to slice

slice is the name of the pipe

start is the start position/index from where the slicing will start

end is the ending index/position in the array/string

The slice pipes take two arguments. The first argument start is the starting index of the string/array. The second argument end is the ending index of the string/array. If the start or end index is negative then the index is counted from end of the string/array

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template:`<p>Complete String :{{msg}} </p>
              <p>Example 1 :{{msg | slice:11:20}} </p>
              <p>Example 2 :{{msg | slice:-9}} </p>`
})
 
export class AppComponent
{
    title: string = 'Angular 2 pipes Example' ;
    msg: string= 'Welcome to Angular 2';
}
 

Both the above examples will display Angular 2. You can read more about slice from this link

DecimalPipe / NumberPipe

The Decimal Pipe is used to Format a number as Text. This pipe will format the number according to locale rules.

Syntax

1
2
3
 
number_expression | number[:digitInfo]
 

Where

number_expression is the number you want to format

number is the name of the pipe

digitInfo is a string which has the following format

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

Where

minIntegerDigits is the minimum number of integer digits to use. Defaults to 1.

minFractionDigits is the minimum number of digits after fraction. Defaults to 0.

maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template: `<p> Unformatted :{{num}}</p>
               <p> Formatted :{{num | number}}</p>
               <p> Formatted :{{num | number:'3.1-2'}}</p>
               <p> Formatted :{{num | number:'7.1-5'}} </p>`
})
 
export class AppComponent
{
    title: string = 'Angular 2 pipes Example' ;
    num: number= 9542.14554;
}
 

PercentePipe

Formats the given number as a percentage according to locale rules.

1
2
3
 
number_expression | percent[:digitInfo]
 

Where

number_expression is the number you want to format

percent is the name of the pipe

digitInfo is a string which has the following format. It is similar to used in decimal pipe

Example code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
 
@Component({
    selector: 'app-root',
    template:`<p>Unformatted :{{per}} </p>
              <p>Example 1 :{{per | percent }} </p>
              <p>Example 2 :{{per | percent:'1.2-2'}} </p>`
})
export class AppComponent
{
    title: string = 'Angular 2 pipes Example' ;
    per: number= .7414;2';
}
 

More about Percent pipe from the link

CurrencyPipe

Formats a number as currency using locale rules.

1
2
3
 
number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]
 

Where

number_expression currency to format a number as currency.

Currency is the name of the pipe

currencyCode is the ISO 4217 currency code, such as USD for the US dollar and EUR for the euro.

symbolDisplay is a boolean indicating whether to use the currency symbol or code. Use true to display symbol and false to use code

digitInfo is similar to the one used in decimal pipe

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
    selector: 'app-root',
    template: `<p>Unformatted :{{cur}} </p>
               <p>Example 1 :{{cur | currency }} </p>
               <p>Example 2 :{{cur | currency:'INR':true:'4.2-2'}} </p>`
})
 
export class AppComponent
{
    title: string = 'Angular 2 pipes Example' ;
    cur: number= 175;
}
 

Read more about the currencyPipe from the link

ngStyle Directive
Angular 2 Custom Pipes
 

Filed Under: Angular Tagged With: pipes

3
Leave a Reply

wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.
2 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Mika Kaakinen

Excellent tutorial. Thank you!

Vote Up0Vote Down  Reply
August 19, 2017 8:27 pm
Tiago A.

How apply a pipe in a FormControl?

Vote Up0Vote Down  Reply
May 18, 2017 12:30 am
TekTutorialsHub

Please take a look at this article
http://stackoverflow.com/questions/42254077/angular-2-date-pipe-inside-a-formcontrol-input

Vote Up0Vote Down  Reply
May 19, 2017 9:11 am

Primary Sidebar

Copyright ©2008-2018

About us Contact Privacy Policy

Feb,22,2019 08:19:28 AM

Copyright © 2019 · Magazine Pro on Genesis Framework · WordPress · Log in

wpDiscuz
Our web site uses cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.OkRead more