Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: September 8, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Pipes in Angular is one of the phrases you will encounter often as you build user interfaces using Angular. What are they, and how do they work?

Angular is among the top 5 most desired web frameworks and technologies based on the StackOverflow survey

The modular architecture makes Angular a darling to developers, allowing them to break the application into small, reusable components. A modular codebase is easy to maintain and also enhances collaboration. The two-way data binding, cross-browser compatibility, and the big ecosystem and community are other reasons why Angular is among the best front-end frameworks. 

This article discusses what Pipes in Angular are, their use cases, different types of built-in Pipes, and how to create custom Pipes in Angular. 

What are Pipes in Angular?

What-are-Pipes-in-Angular

Pipes are a feature in Angular that transforms and formats data in an application. Pipes simply take a value as an input and return a transformed value as output. Transformation varies, and it can be as simple as transforming a currency or date or sorting or filtering items from a list. 

Pipes are designed to enhance user experience as they transform data and return values that users can consume and interact with easily. Pipes in Angular can either be built-in or custom. Irrespective of the type, these are some of the reasons why you should use pipes in Angular:

  • Transform data: This is the main use of Pipes in Angular. Pipes are there to transform data so that what is displayed to users is readable. 
  • Code readability and maintainability: Most applications are built through collaboration. As such, you must ensure that the other team members understand your code. Pipes make your code more concise and easy to maintain. 
  • Localization: You can localize data to suit the target market. For instance, there exist different date formats. Thus, you can use DatePipe to format data to suit the users’ locale. 
  • Sorting and filtering data: You can use OrderPipe or FilterPipe to sort or filter your data. 

Types of Built-in Pipes in Angular

Angular has various built-in pipes designed for different purposes. These are examples of some that you will encounter in your development journey. 

  • PercentPipe: This is the pipe to use when you want to transform a number into a percentage string.
  • DatePipe: This is the pipe to use to format a date value based on locale rules.
  • LowerCasePipe: Transform all your text to your lowercase using this pipe. 
  • UpperCasePipe: You can use this pipe when you want to change all your text to uppercase. 
  • CurrencyPipe: It is a perfect choice when you want to change a number to a currency string based on locale rules. 
  • DecimalPipe: This pipe uses locale rules to transform a number into a string with a decimal point. 

Create Custom Pipes in Angular

We have seen built-in pipes and their use cases. However, Angular supports custom pipes. Such pipes are important when you want to achieve something the built-in pipes cannot achieve. Such pipes allow you to extend the functionality of your application. 

Prerequisites

Before you start building custom Pipes in Angular, you need the following:

  • Node.js runtime environment for your Angular application. You can download Node.js if you don’t have it. 
  • Understanding of how Angular works
  • Angular CLI to create your application and run different commands. You can install it using this command;

npm install -g @angular/cli

Follow these steps to build a custom Pipe in Angular:

#1. Create a new Angular project. You can use this command to get started:

ng new pipes

#2. Change the directory into your created app and open it in your favorite code editor. I am using VsCode. You can run these commands 

cd pipes && code . 

Your project folder will be similar to this;

Angular Project

#3. Create a custom pipe. You can use this command to generate a new custom pipe:

ng generate pipe custom-pipe

If you check your project folder, you will note that these two files have been created:

src/app/custom-pipe.pipe.spec.ts

src/app/custom-pipe.pipe.ts

#4. Define the pipe’s logic

Open the custom-pipe.pipe.ts file and you will find this code:

CustomPipe code example

We can now create a simple logic where our custom pipe is appended to a string. 

You can change the contents of your file to be;

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'customPipe'
})
export class CustomPipePipe implements PipeTransform {
  transform(value: string): string[] {
    return value.split('');
  }
}

#5. Register the custom pipe. Open the app.module.ts file and check you have @NgModule and then decorations. 

Confirm that this file has this code;

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomPipePipe } from './custom-pipe.pipe';

@NgModule({
  declarations: [
    AppComponent,
    CustomPipePipe
  ],

  imports: [
    BrowserModule,
    AppRoutingModule
  ],

  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

#6. Open app.component.html, delete all the content and add this line;

<header>{{ '12345' | customPipe }}</header>

Run the server using this command;

ng serve

This is what will be displayed on your browser;

Stringfied Output

How to Chain Pipes in Angular

Pipe chaining allows you to perform multiple operations with a single expression. We use the pipe operator ( | ) to combine different pipes in Angular. 

We can chain pipes for the following reasons:

  • Chained pipes promote code reusability and modularity: You can set each pipe to perform a specific transformation you can reuse in your application. 
  • Maintain clean code: Chaining templates allow you to keep your code concise, clean, and readable. 
  • Customization: Pipe chaining allows you to combine custom and built-in pipes and customize them to suit your needs. 
  • Complex transformations: Instead of setting one pipe to perform multiple transformations, you can set up several pipes to achieve complex transformations. 

You can chain your custom pipe with another one or a built-in pipe. I can chain the pipe we created earlier customPipe with a built-in lowercase pipe. This is how we can do it:

<p>{{ dataValue | customPipe | lowercase }}</p>

Pure vs. Impure Pipes 

There are two types of pipes in Angular: pure and impure pipes

Pure pipes 

Pipes in Angular are pure by default. A pure pipe is expected to return the same output for the same input. Such a pipe is expected to be deterministic and stateless. 

Angular’s change detection mechanism automatically optimizes pure pipes. Angular does not re-run the pipe transformation unless the input to a pure pipe changes. 

This is how you declare a pipe as pure;

@Pipe({
  name: 'uppercase',
  pure: true

})

export class UppercasePipe {
  transform(value: string): string {
    return value.toUpperCase();
  }
}

As you can see, we have set the pure property of the @Pipe decorator to true.

Impure pipes 

An impure pipe will execute any time Angular detects a change. Such a change does not have to be from the inputs. Impure pipes fit situations that require access to the app’s current state. Accessing a database or making an HTTP request are perfect examples of where you can use impure pipes. 

This is an example of an impure pipe: 

@Pipe({
  name: 'sort',
  pure: false
})

export class SortPipe {
  transform(array: any[]): any[] {
    return array.sort();
  }
}

As you can see, we have set the pure property of the @Pipe decorator to false make our pipe impure. 

Creating Pipes in Angular: Best Practices

  • camelCase your pipes: If you have noted, I have named my pipe customPipe. Always use this approach if your pipe has more than one word. 
  • Test your pipes: Creating a pipe does not guarantee it will work. Always test your pipes to ensure they are working as expected. You can automate this process using various libraries. 
  • Avoid complex pipes: You may want one pipe to perform more than one action. However, this is not a good approach, and the best practice is creating different pipes to perform different actions. 
  • Use pure pipes: A pure pipe will always return the same output from the same input. Angular can cache results for pure pipes, which results in an improvement in performance and response time. 

FAQs

Why do we need Pipes in Angular?

Pipes transform and format data in an application. Pipes take a value as an input and return a transformed value as output. Transformation varies, and it can be as simple as transforming a currency or date or sorting or filtering items from a list.

What is a custom pipe?

This is a user-defined pipe that you create to perform custom transformations. You can combine a custom pipe with built-in pipes through pipe chaining. 

Give examples of built-in pipes in Angular. 

DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, DecimalPipe and PercentPipe

What is pipe chaining?

Pipe chaining is the process of combining several chains. Pipe chaining allows you to perform multiple operations with a single expression. We use the pipe operator ( | ) to combine different pipes in Angular. You can chain custom pipes with others or chain them with built-in pipes

Conclusion 

We believe you can now describe pipes in your next interview, as this is a regular question in Angular frequently asked questions. We have also covered the different built-in Pipes and how to create custom pipes in Angular.

Custom pipes will be useful when you want to address specific needs or make your application more dynamic. However, you must understand how Angular works under the hood to create and use custom pipes. 

You may also explore some Angular UI libraries to create a world-class user experience.

  • Titus Kamunya
    Author
    Titus is a Software Engineer and Technical Writer. He develops web apps and writes on SaaS, React, HTML, CSS, JavaScript, Ruby and Ruby on Rails read more
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder