Skip to main content

Related Articles

Angular Pipes

angular pipes "|"

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.

  1. Uppercase pipe
  2. Lowercase pipe
  3. Date pipe
  4. Currency pipe
  5. Percent pipe
  6. Decimal pipe
  7. Slice pipe

After setting up the environment and creating the example app we will try out each default pipe provided by Angular framework.


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>UPPERCASE</h1>
  <h2>
   Welcome to {{ title|uppercase }}
 </h2>
angular uppercase pipe example
2. Lowercase Pipe
<h1>LOWERCASE</h1>
  <h2>
    Welcome to {{ title|lowercase }}
 </h2>


angular lowercase pipe example
3. Date pipe

Below example will show you how you can use default date pipe for different formats of date values and its output.

<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>
angular date pipe example

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>
angular currency pipe example
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

angular percent pipe example

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
angular decimal pipe example
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>
angular slice pipe example

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.

creating a custom pipe formatnumber_ts

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>
before and after apply angular custom pipe

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

Popular posts from this blog

The Power of ChatGPT and Whisper Models

A Deep Dive into Natural Language Processing Natural Language Processing (NLP) has seen a significant boost in recent years due to advancements in artificial intelligence and machine learning. Two models that have shown remarkable success in NLP are ChatGPT and Whisper. In this article, we will delve into the power of these models and their applications in the field of NLP. ChatGPT is a transformer-based language model developed by OpenAI that uses unsupervised learning to predict the next word in a sentence based on the context of previous words. ChatGPT is a generative model that is trained on large datasets of text, such as books and articles, and can be fine-tuned for specific tasks, such as question-answering or dialogue generation. ChatGPT is known for its ability to produce human-like text, making it an ideal tool for applications such as chatbots, content creation, and language translation. Whisper, on the other hand, is a paraphrasing model developed by Google that is based on

Building robust APIs with Node.js

Node.js is a popular open-source JavaScript runtime environment that allows developers to build scalable and high-performance web applications. One of the key strengths of Node.js is its ability to build APIs quickly and efficiently. APIs, or Application Programming Interfaces, allow different systems to communicate with each other, enabling data exchange and other operations. Building robust APIs with Node.js requires an understanding of RESTful architecture, which is a widely adopted standard for creating APIs. RESTful APIs provide a standardized way to expose data and functionality over the web using a set of HTTP methods such as GET, POST, PUT, and DELETE. To build a robust Node.js API, developers must choose an appropriate framework and set up a development environment. They should also handle errors and exceptions, implement authentication and authorization, and use middleware to enhance the functionality of the API. Writing test cases, documenting the API using tools such as Swa

DevOps automation using Python - Part 2

Please read  DevOps automation using Python - Part 1 article before this article, since this is a continuation the same. Introduction to network automation with Python and Netmiko Network automation involves automating the tasks of network devices such as switches, routers, and firewalls to improve efficiency and reduce errors. Python is a popular programming language used for network automation due to its simplicity and ease of use. Netmiko is a Python library used to automate network devices that support SSH connections. In this article, we will provide an introduction to network automation with Python and Netmiko . Setting up Python and Netmiko To get started, you will need to install Python on your machine. You can download the latest version of Python from the official website ( https://www.python.org/downloads/ ) and install it according to the installation instructions for your operating system. Once you have installed Python, you can install Netmiko using pip, a Python package