Tuesday, October 18, 2022

Angular Pipes With Examples

Using Angular pipes you can transform data like strings, currency amounts, dates, many other values for display. You use pipe symbol (|) for Angular pipes and syntax is as follows.

value_expression | Angular pipe

For example there is a built-in Angular pipe named UpperCasePipe which is used to transform text to all upper case, let’s say there is a field ‘name’ which you want to display in uppercase then you’ll use this pipe as given below.

{{ name | uppercase}}

Built-in Angular pipes

Angular framework has many built-in pipes that can be used as per requirement.

Pipe Name Description
AsyncPipeAdditive operator (also used for String concatenation)
CurrencyPipeTransforms a number to a currency string
DatePipeFormats a date value according to locale rules.
DecimalPipeTransforms a decimal number into a string, formatted according to locale rules
I18nPluralPipeMaps a value to a string that pluralizes the value according to locale rules.
I18nSelectPipeGeneric selector that displays the string that matches the current value.
JsonPipeConverts a value into its JSON-format representation. Useful for debugging.
KeyValuePipeTransforms Object or Map into an array of key value pairs.
LowerCasePipeTransforms text to all lower case.
PercentPipeTransforms a number to a formatted percentage string.
SlicePipeCreates a new Array or String containing a subset (slice) of the elements.
TitleCasePipeTransforms text to title case. Capitalizes the first letter of each word and transforms the rest of the word to lower case.
UpperCasePipeTransforms text to all upper case.

UpperCasePipe and LowerCasePipe example

For the example we’ll create a JSON object in the Component class and while displaying the values in the template we’ll use the pipes to transform the data.

Component Class (app.component.ts)

import { Component, OnInit } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html', 
export class AppComponent{
  user = {
      firstName: 'john',
      lastName: 'doe',
      dept: 'FINANCE',
      amount: 456.789,      
      doj: new Date('2015-12-11')    

Template (app.component.html)

<div class="container">
  <h1>User Details</h1>
  <div class="row">
    <div class="col-sm-4">
      <label><strong>First Name:</strong> </label> {{ user.firstName | uppercase}}      
    <div class="col-sm-4">
      <label><strong>Last Name: </strong></label> {{ user.lastName }}
  <div class="row">
    <div class="col-sm-4">
      <label><strong>Department: </strong></label> {{ user.dept | lowercase }}      
    <div class="col-sm-4">
      <label><strong>Amount: </strong></label> {{ user.amount }}
  <div class="row">
    <div class="col-sm-4">
      <label><strong>Date of Joining: </strong></label> {{ user.doj }}      

Pipes with parameters

Though Uppercase and Lowercase pipes don’t have any parameters but pipes like date and currency also use optional parameters to further fine-tune a pipe’s output. Parameter value is provided by using colon (:) after the pipe name, for example

{{ amount | currency:'EUR' }}

You can provide more than one parameter too. If the pipe accepts multiple parameters, separate the values with colons.

For example syntax of DatePipe is as given below, giving you option to provide parameters for date format, timezone and locale.

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

DatePipe Angular example

For formatting date there are many pre-defined format options like-

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).

You can also pass custom format option using symbols y, M and d for year, month and day, using H, m and s for hour, minute and second.

For all the pre-defined format options and custom format options check documentation here.

For doj: new Date('2015-12-11') we’ll get formatted outputs as-

{{ user.doj | date:'full' }} //Friday, December 11, 2015 at 5:30:00 AM GMT+05:30
{{ user.doj | date:'medium' }} //Dec 11, 2015, 5:30:00 AM
{{ user.doj | date:'MM-dd-yyyy HH:mm:ss' }}  // 12-11-2015 05:30:00
{{ user.doj | date:'MM-dd-yyyy HH:mm:ss z' }}  // 12-11-2015 05:30:00 GMT+5

CurrencyPipe Angular example

Currency pipe is used to format currencies. First parameter is the currency code like ‘USD’, ‘CAD’, ‘EUR’, second parameter is to specify whether you want to display code or symbol.

For amount: 456.789 here are some currency formatting Angular examples

{{ user.amount | currency : 'USD': 'symbol'}} //$456.79
// equivalent to 'symbol'
{{ user.amount | currency : 'USD': true}} //$456.79
// displays currency code
{{ user.amount | currency : 'USD': 'code'}} //USD456.79
// digit info param is also used
{{ user.amount | currency:'USD':'code':'4.1-3'}} // USD0,456.789
{{ user.amount | currency:'EUR':true:'4.1-1'}} // €0,456.8

DecimalPipe Angular example

DecimalPipe is used to transform number into string with formatting for decimal digits.

For field amount: 456.789 here are some decimal formatting Angular examples

{{ user.amount | number:'3.1-2'}} //456.79
{{ user.amount | number:'4.0-0'}} // 0,457

JsonPipe Angular example

You can use this pipe to Converts a value into its JSON-format.

For example if we have a user object as given below

user = {
      firstName: 'john',
      lastName: 'doe',
      dept: 'FINANCE',
      amount: 456.789,
      doj: new Date('2015-12-11')

Then using the JsonPipe- {{ user | json }} gives output as-

{ "firstName": "john", "lastName": "doe", "dept": "FINANCE", "amount": 456.789, "doj": "2015-12-11T00:00:00.000Z" }

PercentPipe Angular example

PercentPipe is used to transform a number to a percentage string.

{{ 0.23456 | percent}} // 23%
{{ 1.3467 | percent }} // 135%
{{ 0.23456 | percent:'3.3-5'}} //023.456% 
{{ 1.3467 | percent:'3.3-5'}} //134.670%

SlicePipe Angular example

Using SlicePipe you can create a new array or string by slicing the original value. You can pass start and end positions for slicing.

// Providing only start index
{{ [1,2,3,10,11,12] | slice:3}} // 10,11,12
// Providing both start and end
{{ 'Angular' | slice:3:5}} // ul

Chaining multiple pipes

You can chain multiple pipes so that the output of one pipe becomes the input to the next. For providing more than one pipe separate pipe names by ‘|’ symbol. For example using both DatePipe and UpperCasePipe.

{{ user.doj | date:'full' | uppercase}}  // FRIDAY, DECEMBER 11, 2015 AT 5:30:00 AM GMT+05:30
where user object is defined as-
 user = {
      firstName: 'john',
      lastName: 'doe',
      dept: 'FINANCE',
      amount: 456.789,
      doj: new Date('2015-12-11')

That's all for this topic Angular Pipes With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page

Related Topics

  1. Using Angular Pipes in Component or Service Classes
  2. Custom Pipe in Angular With Example
  3. Pure and Impure Pipes in Angular
  4. Async Pipe in Angular With Examples
  5. CanDeactivate Guard in Angular With Example

You may also like-

  1. Creating New Component in Angular
  2. Forms in Angular
  3. Service in Angular With Examples
  4. Angular Routing Concepts With Example
  5. Java Exception Handling Interview Questions And Answers
  6. static Method Overloading or Overriding in Java
  7. How to Sort a HashMap in Java
  8. self in Python

No comments:

Post a Comment