Site icon codippa

Pipes in angular / How to use pipes in angular

What are Pipes?
Pipes are a way to transform or modify the data that is shown to the user. Typically, pipes perform utility functions by using a simple syntax which would otherwise require some coding. Example, suppose you want to show the name of an employee or some object in upper case, no matter in which case you are getting it from the backend source or you want to format a large number properly with commas according to its length(such as 1,23,000). Using pipes, this can be easily done.

Syntax
Pipes are applied to the data to be transformed by using pipe symbol( ) followed by the name of pipe. 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 pipes as per customized needs. Following are the pipes provided by angular.

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

{{ component_variable / value | uppercase }}

Example, {{ myVar | uppercase }}

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

{{ component_variable / value | uppercase }}

Example, {{ myVar | uppercase }}

3. currency
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)
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
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 
This pipe is used for transforming date in required format. A date can have many formats such as
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
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
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
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
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. At anytime 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 post helped you out to learn about the requirement, usage of pipes and details about the built-in pipes provided by angular.
Exit mobile version