Angular pipe

Pipes in angular are used for transforming the data. A pipe takes an input and transforms or converts it to required output format.

Some examples or usage of pipes are
1. Convert an input string into upper case or lower case.
2. Convert an input date to a required format.
3. Accept a string input and highlight a particular search text.
4. Format a number according to currency etc.

Syntax
Angular pipe is used with below syntax.

{{ input | pipe name }}

As evident from the above syntax, a pipe syntax is composed of following parts.

1. Input:  Value on which the pipe operation will be applied. An angular pipe can accept a string, date, array and integer as input.
2. Pipe Name:  Given while creating a pipe using @Pipe directive. This directive is applied over the component class of the pipe.
3. Input value and pipe name are separated by pipe symbol(|) and enclosed between double curly braces.

Result or pipe output is directly written to the browser due to String interpolation.

Example, if the name of pipe is uppercase, then it will be applied as shown below

{{ “codippa” | uppercase }}

Result will be CODIPPA. Here codippa is a string. A pipe can also be applied to a variable in the component class such as

{{ myVar | uppercase }}

In this case, the text rendered will be the value stored in variable myVar in upper case.
Also, since, text is to be displayed on the web page, the data along with pipe syntax must be enclosed within double curly braces {{ and }}. This is called Interpolation.

Built-in Pipes
Angular supplies different built-in pipes which are sufficient for most purposes. It is also possible to create our own custom pipes as per need.

Following are the pipes provided by angular.

1. uppercase pipe
It converts the data supplied to it in upper case. Syntax is

{{ component_variable / value | uppercase }}

Example,

<!– result will be CODIPPA –>
{{ “codippa” | uppercase }}

A variable from component typescript class can also be used as shown below.

{{ myVar | uppercase }}

where myVar is a variable defined in the component class.

2. lowercase pipe
It transforms the value supplied to it in lowercase. Syntax is

{{ component_variable / value | uppercase }}

Example, {{ myVar | uppercase }}

3. currency pipe
Used to transform a number is currency format such as adding commas and adding currency symbol or notation.

It has several options some of which are explained below.

<!– display in Australian dollar –>

<div>{{ 34562 | currency: ‘AUD’}}</div>


<!– same as above –>

<div>{{ 34562 | currency: ‘AUD’: ‘symbol’}}</div>


<!– display symbol in short format –>

<div>{{ 34562 | currency: ‘AUD’: ‘symbol-narrow’}}</div>


<!– display 6 digits before decimal and 2 digits after decimal –>
<div>{{ 34562 | currency: ‘AUD’: ‘symbol’: ‘6.2’}}</div>
Above code will generate the following output
A$34,562.00
A$34,562.00
$34,562.00
A$034,562.00

Note that the input to the pipe can also come from a variable declared in the component class.
For complete list of currency codes, refer this link.

4. number(also called decimal) pipe
Transforms the supplied value into formatted number by adding commas at appropriate places.
It can also be used to format a decimal number for displaying the required number of digits before and after decimal.
Examples are
<!– display formatted number, output will be 34,562 –>
<div>{{ 34562 | number }}</div>

<!– display formatted decimal, output will be 1,234.562 –>
<div>{{ 1234.562 | number }}</div>

<!– display 2 digits before decimal and max 2 digits after it, output will be 34.56 –>
<div>{{ 34.562 | number: ‘2.1-2’ }}</div>

<!– display 2 digits before decimal and 1 digit after it, output will be 34.6 –>
<div>{{ 34.562 | number: ‘2.1-1’ }}</div>

Giving just the pipe name will add commas to the number.

A decimal number can be formatted to display the required number of digits both before and after the decimal.
Syntax to format a decimal is :

{{value | number:'[number of digits before decimal].[min number of digits after decimal] – [max number of digits after decimal] }}

Default value for digits before decimal is 1, for minimum digits after decimal is 0 and for maximum digits after decimal is 3.

Note that minimum number of digits should be less than the max number of digits else it will be an error. Example, following pipe will raise an error on the console

<div>{{ 34.562 | number: ‘2.3-2’ }}</div>

Error: The minimum number of digits after fraction (3) is higher than the maximum (2).

Also, if the number of digits given in the pipe are less than that after decimal in the actual number, then final result will be rounded off to nearest decimal.
Example, consider the following two pipes
<!– output will be 34.56 –>

<div>{{ 34.562 | number: ‘2.1-2’ }}</div>

<!– output will be 34.57–>
<div>{{ 34.567 | number: ‘2.1-2’ }}</div>
5. percent pipe
This pipe is used to format values in percentage. Similar to number pipe, it also has the options to format digits after decimal.
Syntax to format a value into percentage is

{{ value | percent }}

Syntax with additional options to format decimal values is

{{value | percent :'[number of digits before decimal].[min number of digits after decimal] – [max number of digits after decimal] }}

Note that this pipe multiplies the supplied value by 100 in order to convert it to a percent and adds percentage symbol( % ) to the output.
Let’s take a look at some examples,
<!– display formatted percent, output will be 34% (supplied value multiplied by 100)–>

<div>{{ .34 | percent }}</div>

 

<!– display formatted percent, output will be 3,400% (supplied value multiplied by 100) –>
<div>{{ 34 | percent }}</div>

<!– display formatted decimal, output will be 34.562% –>
<div>{{ .34562 | percent: ‘2.2-3’ }}</div>

<!– display 2 digits before decimal and max 2 digits after it, , output will be 34.56%–>
<div>{{ .34562 | percent: ‘2.1-2’ }}</div>

<!– display 2 digits before decimal and 1 digit after it, , output will be 34.6%–>
<div>{{ .34562 | percent: ‘2.1-1’ }}</div>
Similar to the number pipe, this one also rounds off the result as per the number of digits which should become clear with the examples above.
6. date pipe
This pipe is used for transforming date in required format. A date can have many formats such as
  • date, month name in alphabets, year.
  • date, month and year in various numeric formats such as dd/MM/yyyy or dd-MM-yy or yyyy/MM/dd etc.
  • date, month and year along with time in different formats.
  • Only time without date and many more.
Using date pipe, a given date can be displayed in any of the above formats using the various options provided by this pipe.
Basic syntax of using a date pipe is

{{ variable / value | date }}

Below example will clarify the usage of date pipe

import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   template:`
     <div>Unformatted date: {{ today }}</div>
     <div>Today is {{today | date }}</div>
     <div> Full date: {{today | date : 'fullDate'}}</div>
     <div> Medium date: {{today | date : 'medium'}}</div>
     <div> Short date: {{today | date : 'short'}}</div>
     <div> Date in dd/MM/yyyy format: {{today | date : 'dd/MM/yyyy'}}</div>
     <div> Time in hh:mm:ss format: {{today | date : 'hh:mm:ss'}}</div>
     `,
   styleUrls: ['./app.component.css']
})
export class AppComponent {
      today = new Date(Date.now());
}

 

Output of the above template is

Unformatted date: Sun Sep 09 2018 16:46:12 GMT+0530 (India Standard Time)
Today is Sep 9, 2018
Full date: Sunday, September 9, 2018
Medium date: Sep 9, 2018, 4:46:12 PM
Short date: 9/9/18, 4:46 PM
Date in dd/MM/yyyy format: 09/09/2018
Time in hh:mm:ss format: 04:46:12
Details about all the available options can be found from angular documentation about date pipe.
7. titlecase pipe
This pipe transforms the string provided to it into title case meaning, it capitalizes the first letter of each word of the string.
Syntax is

{{ variable / value | titlecase }}

Example,
<!– output will be First Letter Will Be Capital –>
<div>{{‘first letter will be capital’ | titlecase }}</div>
8. json pipe
This pipe converts the supplied object into its corresponding json representation. Syntax of usage is

{{ variable / value | json }}

Example,
import { Component } from '@angular/core';
@Component({
   selector:'app-root',
   template:`
      <div>Normal object: {{ employee }}</div>
      <div>Using pipe: {{ employee | json }}</div>
   `,
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   employee= {
      name:'emp',
      id:1,
      department:'java'
   };
}

Output of above component’s template is

Normal object: [object Object]
Using pipe: { “name”: “emp”, “id”: 1, “department”: “java” }
9. slice pipe
This pipe is used to extract a sub-set of the value or expression supplied to it.
The value may be a string, an array or a collection of elements. It slices the value on the basis of indexes given to it.
Syntax is

{{ variable / value | slice : startIndex : endIndex }}

Starting index is counted from 0 and value is sliced till endIndex – 1. Also, endIndex is optional, if not given, then the value is sliced starting from the startIndex till the end of value.
Examples would make it more clear.
<!– result will be 2,4, starting from 1st index of array till 2nd –>
<div>{{ [1,2,4,6,4] | slice:1:3 }}</div>
<!– result will be sc starting from 1st index of string till 2nd –>
<div>{{‘ascxzx’ | slice:1:3 }}</div>
<!– result will be scxzx starting from 1st index of string till end –>
<div>{{‘ascxzx’ | slice:1 }}</div>

If the values of start and end index are negative, then they are assumed to be starting from the right of the value, that is, -1 index is of the rightmost or last character, -2 index is of the second last character, -3 index is of the third last character or the third character from right and so on.

Parsing of the value is done from left to right or start index should be less than end index. Examples,

<!– will return the last character since endIndex is not given –>
<div>{{‘ascxzx’ | slice:-1 }}</div>
<!– will return xz the third last character or third character from right
till second last character –>
<div>{{‘ascxzy’ | slice:-3:-1 }}</div>
<!– will return nothing since start index is not less than end index –>
<div>{{‘ascxzy’ | slice:-1:-3 }}</div>
Pipe Chaining
It is possible to use multiple pipes in a single expression one after another.
In this case the output of one pipe is the input to another pipe starting from left to right and the final output is a combination of results of all the pipes.
This is called Chaining of Pipes in angular. Example,
<!– result will be SC –>
<div>{{‘ascxzx’ | slice:1:3 | uppercase }}</div>

<!– result will be 12% –>
<div>{{‘0.123’ | slice:1 | percent }}</div>
Hope this article helped you out to learn about pipes in angular and how to use them along with details about the built-in pipes provided by angular.

Leave a Reply