05
OctWhat are Pipes in Angular - Pure & Impure Pipe in Angular (With Example
Exploring Pipes in Angular: An Overview
An effective tool in Angular for changing data inside templates is pipes. They provide a practical means of organizing, screening, and modifying data before its presentation to consumers. Explore online resources such as Angular Tutorials and Angular Certification Courses for more in-depth information.
What are Pipes in Angular?
Pipes are functions in Angular that take in input data and provide altered output data. They can be used to filter and sort arrays and format dates, integers, strings, and other kinds of data within template expressions. Pipes improve the presentation layer of Angular applications and make data handling easier.
A simple example of a pipe would be like:
Import {Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<h2>Her birth date is {{ birthdate | date }}</h2>`
})
export class AppComponent {
birthdate = new Date(1996, 5, 5);
}
In the above example, we have used a pipe operator on the birthdate by interpolation. Here, we used the Date pipe function on the right.
Commonly Used Built-in Pipes
Angular provides various built-in pipes that can be used typically for data transformations, including currency, decimal, upper and lower case along with transformations for internationalization, which use locale information to format data. The following are commonly used built-in pipes for data formatting:
- Currency Pipe
- Date Pipe
- Json Pipe
- LowerCase Pipe
- UpperCase Pipe
- PercentPipe
- SlicePipe
- TitleCasePipe
- AsyncPipe
Let us see some of them next.
1. Slice - used for a list or a string to be sliced.
{{ value_expression | slice : start : end }}
Some of the parameters used with this pipe function are:
start (the starting index of the subset to return)
end (the ending index of the subset to return)
2. UpperCase -Transforms text to upper case format.
{{ value_expression | uppercase }}
3. Currency - Transforms a number to a currency string
{{ value_expression | currency }}
Some of the parameters used with this pipe function are:
currencyCode
display
digitsinfo
locale
4. JSON - Converts a value into its JSON-format representation
{{ value_expression | json }}
Percent - Percent pipe is used to transform the percent number into the well-formatted string as given below
{{ 0.295 | percent }}
Chaining of pipes
Angular also provides us the feature to use two or more pipe functions together in a useful combination. This process is known as the Chaining of pipes.
{{ birthdate | date | lowercase}}
We can also parameterize pipes using the ":" after the pipe function like:
date: 'fullDate' or {{ num | percent [ : digitsInfo ] }}
Creating Custom Pipes
Another interesting concept with pipes in Angular is that we can create our very own custom pipes and enhance the working of our data. Steps Involved In Creating a Custom Pipe In Angular are
Create a Pipe Class and decorate it with the decorator @Pipe.
Supply a name property to be used as a template code name.
Register your Pipe in the module under-declarations.
Finally, implement PipeTransform and write transformation logic.
Use your pipe in the HTML using ‘|’, which represents a pipe.
Also, add Custom arguments if you want to.
import { Pipe } from '@angular/core';
@Pipe({
name: 'demo'
})
export class DemoPipe{ }
Once we are done creating the Pipe class, we go to app.module.ts and register our pipe.
import { DemoPipe } from './demo.pipe';
@NgModule({
declarations: [
DemoPipe
],
imports: [
BrowserModule
],
To finally put some logic behind the task of our custom pipe, we use PipeTransform.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'demo'
})
export class DemoPipe implements PipeTransform{
transform(n: number) {}
}
So, to maintain the required standard structure, we use the transform() method inside PipeTransform.Now, our motive is to convert some random number to a readable format of kilograms, and to do that, we put logic inside transform() as follows
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'demo'
})
export class DemoPipe implements PipeTransform{
transform() : string {
return (n *1000).toFixed(2) + 'Kg';
}
}
Now to use it in the HTML,
<div>
<p>{{ demo.name }}</p>
<p>{{ demo.n | demo }}</p>
</div>
To add a custom argument to your output, simply add the capability of extension to the Transform() method as follows.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'demo'
})
export class DemoPipe implements PipeTransform{
transform(n: number, extension: string = 'Kilograms') {
return (n * 1000).toFixed(2) + extension;
}
}
This is how you can create a custom pipe for your own.
Types of pipes in Angular
Pipes, in general, have two categories
Pure (all pipes by default are pure)
Impure pipes
Pure pipes are executed when there is a change to the primitive input value or the object reference is changed, whereas Impure pipes are executed during every angular component change detection cycle. (Change Detection is a vast concept in itself which is out of the scope of this article). Some interesting examples of Impure Pipes are:
AsyncPipe (used with Observables)
CachingPipe (used to make HTTP requests)
Best practices for using pipes
- Make use of built-in pipes: To reduce overhead, make use of Angular's optimized built-in pipes, such as DatePipe, CurrencyPipe, and DecimalPipe.
- Avoid excessive chaining: Limit pipe chaining to avoid performance issues, particularly when working with big datasets. Instead, think about data preprocessing or bespoke pipes.
- Performance considerations: Minimise pipe calls and steer clear of complex computations inside them.
- Maintain simple pipes: Keep pipelines simple and concentrate on single transformations to make debugging and maintenance easier.
- Pure pipes are preferred: To improve performance, use pure pipes and only call them when the input changes.
- Recognize the different data types: To guarantee proper behavior, be aware of the data types that various pipes demand.
- Conduct a comprehensive test: Perform thorough testing, including component and unit testing, on custom pipelines to ensure functioning and integration.
Read More:
Summary
This blog post explains how using a pipe, we can transform data and display it to the user. It also discussed the use of built-in pipes in Angular like DatePipe, PercentPipe, etc., and how we can create and use Custom pipes to enhance the working of our Angular projects with the code examples. By the end of the article, some light was put on Pure and Impure Pipes and their examples.
FAQs
Q1. What is the Angular pipe method?
Q2. In what context does Angular use pipes?
Q3. How can I use Angular to call a pipe?
Take our Angular skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.