Search⌘ K
AI Features

Building Custom Pipes

Explore how to create custom pipes in Angular to modify and sort data dynamically within your application. Learn to use the Angular CLI to generate pipes, implement the PipeTransform interface, and apply your pipe in component templates for enhanced data handling and presentation.

We'll cover the following...

In this lesson, we are going to dive deeper into how we can build a pipe to provide custom transformations to data bindings. We will create a pipe that sorts our list of products by name.

Sorting data by building a custom pipe

To create a new pipe, we use the generate command of the Angular CLI, passing the word pipe and its name as parameters:

Note: The command below is for creating a pipe on the local machine using the Angular CLI.

ng generate pipe sort
Command to create a pipe

When we run the preceding command in the src\app\products folder, it will create the sort.pipe.ts file and its corresponding unit test file, sort.pipe.spec.ts. It will also register the pipe with the associated ProductsModule in the products.module.ts file:

TypeScript 4.9.5
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductListComponent } from './product-list/product-list.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';
import { SortPipe } from './sort.pipe';
@NgModule({
declarations: [
ProductListComponent,
ProductDetailComponent,
SortPipe
],
imports: [
CommonModule
],
exports: [ProductListComponent]
})
export class ProductsModule { }

A pipe is added in the declarations array of an Angular ...