×

AngularJS Tutorial

AngularJs Questions

AngularJS Practice

Advertisement


Angular Pipes

In this tutorial, we are going to learn about the pipes and their types. Creating and implementing pipes in Angular.

What are the pipes in angular?

In Angular, pipes are simply a function that takes input data and is used to transform and format the data within a template. They allow you to modify data directly within the template and can be used for common transformations like formatting dates and numbers, as well as manipulating strings, etc.

Syntax

Following is the syntax of the pipe in angular:

{{data | pipe_name}}

Where,

  1. "{{}}" is an interpolation that allows you to bind your data with the component.
  2. "data" is the data that you want to format for transforms.
  3. "|" is a pipe symbol that we use in angular.
  4. "pipe_name" is your pipe name that can be anything such as "uppercase", "lowercase", etc.

There are mainly two types of pipes in angular as follows:

  1. Built-in pipes
  2. Custom pips

Built-in Pipes in Angular

Angular provides a set of built-in pipes for common transformations, which are readily available for use in templates without demanding any additional setup.

Following are lists of the built-in pipes:

  • Date Pipe: This pipe is used to format the date.
  • Decimal Pipe: This pipe is used to format numbers.
  • Currency pipe: This pipe is used to format currencies.
  • UpperCasePipe: Used for converting text into uppercase.
  • LowerCasePipe: Used for converting text into lowercase.
  • PercentPipe: This pipe is used for formatting percentages.
  • JsonPipe: Used for converting JavaScript objects into JSON strings.
Note

To implement and create pipes in your angular project or application, ensure your angular application is ready.

Let's discuss with the help of the code of each built-in pipe for better understanding:

Formatting Date: Using date Pipe

In the example below we use the date pipe to format the current date into 'dd-mm-YYYY' and 'dd/mm/YYYY' formats -

app.component.ts file

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

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
 title = 'myApp';
 date: any;
 ngOnInit(): void {
     this.date = new Date();
 }
}

app.component.html file

<h2>Date: {{date | date : 'dd-mm-YYYY'}}</h2>
<h2>Date: {{date | date : 'dd/mm/YYYY'}}</h2>

Output

Date: 04-7-2024
Date: 04/7/2024

Formatting Decimal: Using decimal Pipe

In this example, we are formatting the decimal (pi value) value using the decimal pipe into 'number' and '1.2-2' formats.

app.componente.ts file

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

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrl: './app.component.css'
})
export class AppComponent {
 pi = 3.14159;
}

app.component.html file

<h2>PI value: {{pi | number}}</h2>
<h2>PI value: {{pi | number: '1.2-2'}}</h2>

Output

PI value: 3.142
PI value: 3.14

Formatting Currency: Using currency Pipe

We will use the currency pipe to format the current price into a currency format.

app.component.ts file

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

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrl: './app.component.css'
})
export class AppComponent {
price = 12343.4554;
}

app.component.html file

<h2>Price (default currency): {{price | currency}}</h2>
<h2>Price (in INR): {{price | currency : 'INR'}}</h2>

Output

Price (default currency): $12,343.46
Price (in INR): ₹12,343.46

Converting Text into Upper and Lower Cases

In the following example, we use the 'uppercase' and 'lowercase' pipes to convert the text into small (lower) and capital (upper) cases.

app.component.ts file

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

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrl: './app.component.css'
})
export class AppComponent {
title = "What are the pipes in Angular ?";
}

app.component.html file

<h2>Uppercase: {{title | uppercase}}</h2>
<h2>Lowercase: {{title | lowercase}}</h2>

Output

Uppercase: WHAT ARE THE PIPES IN ANGULAR ?
Lowercase: what are the pipes in angular ?

Formatting Percent: Using percent Pipe

In the following example, we use the percent pipe to format the current percent rate into the 'percent' and 'percent:'1.2-2'' format.

app.component.ts file

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent{
 discountRate = 12.2423;
}

app.component.html file

<h2>DiscountRate: {{discountRate | percent}}</h2>
<h2>DiscountRate: {{discountRate | percent: '1.2-2'}}</h2>

Output

DiscountRate: 1,224%
DiscountRate: 1,224.23%

Custom Pipes in Angular

In Angular, custom pipes allow you to create reusable and modular transformations for data that is displayed in your templates (HTML).

You can define custom pipes to perform specific formatting, filtering, or other data manipulations that are not covered by the built-in Angular pipes.

Steps to Create Custom Pipes

The following are steps to create a custom pipe in your angular project or application:

Step 1

Create a folder within your app component with the name "pipes" or you can run the following command in your terminal it will automatically create a "pipes" folder in your app component along with the custom file.

Step 2

Run the following command to create a custom pipe along with the folder:

>> ng generate pipe pipes/agePipe

Where,

  • ng generate is the command to generate a pipe, you can specify the folder name where you want to create our custom pipe, we have given folder names as pipes.
  • agePipe is your pipe name, you can keep any name as per your requirement, but make sure the name should be meaningful.

Step 3

After running the above command in your IDE terminal, you might able to see the bellow messages:

CREATE src/app/pipes/age-pipe.pipe.spec.ts (192 bytes)
CREATE src/app/pipes/age-pipe.pipe.ts (219 bytes)
UPDATE src/app/app.module.ts (464 bytes)

Step 4

Now you might able to see two files within your pipes folder as follows:

age-pipe.pipe.spec.ts

import { AgePipePipe } from './age-pipe.pipe';

describe('AgePipePipe', () => {
 it('create an instance', () => {
   const pipe = new AgePipePipe();
   expect(pipe).toBeTruthy();
 });
});

age-pipe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'agePipe'
})

export class AgePipePipe implements PipeTransform {
 transform(value: unknown, ...args: unknown[]): unknown {
   return null;
 }
}

You will write your all logic within the age-pipe.pipe.ts file only.

Step 5

Now open the age-pipe.pipe.ts file and start writing the below code that will format the user age.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'agePipe'
})
export class AgePipePipe implements PipeTransform {

 transform(value: any, ageLimit = 20) {
   const age = new Date().getFullYear() - new Date(value.dob).getFullYear();
   return age > ageLimit;
 }
}

Here, the value is the value of a variable that you want to format using this custom pipe. Loot at the below code for a better understanding.

app.component.ts file

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent{
 users = [
   {
   "name": "Rahul",
   "dob": "04/01/1999"
  },
  {
   "name": "Vinay",
   "dob": "04/01/2018"
  },
  {
   "name": "Lokesh",
   "dob": "04/01/2000"
  }
]
}

app.component.html file

<ul>
   <li *ngFor="let u of users">
     Name: {{ u.name }} | Age > 20: {{ u | agePipe: 20 }}
   </li>
</ul>

Output

  • Name: Rahul | Age > 20: true
  • Name: Vinay | Age > 20: false
  • Name: Lokesh | Age > 20: true

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.