What are pipes in Angular?

Angular pipes

Angular pipes provide a sophisticated way to perform the tasks within the templates. Pipes make the code structured and clean. Pipes take the data as input and transform it into output in the desired way.

The primary purpose of the pipes is the transformation of an existing value and reusability.

Angular pipes

Let’s look at an example.

Example: Date pipe

Suppose we have a pipe that computes age from a given date input, as shown in the image below.

Pipe example

There are many built-in Angular pipes that we can use right away, like the date pipe, uppercase, and lowercase pipes. We can also create custom pipes for customized transformation.

Pipes are used in the templates by using the following syntax:

{{ input | pipeName }}

Let’s see the date example in the code as well to get a better understanding.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Date pipe

Chaining pipes

Note: What if we want the output in Uppercase?

Thankfully, the Angular pipes are “chainable,” so we can think of it like this:

Chaining pipes in Angular
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Chain pipes in Angular

Copyright ©2024 Educative, Inc. All rights reserved