Add a custom pipe to Angular 8

A three-step way to build custom pipes in Angular 8

By: Ajdin Imsirovic 22 August 2019

In this short article, you’ll see how to add a custom pipe to your Angular app. The purpose of a custom pipe is some custom formatting on your data.

View the finished example on Stackblitz

For this simple demonstration, we’ll be using the Stackblitz website, and it’s default Angular barebones app. The only twist here is: Instead of showing “Hello Angular!” on the screen, we’ll show just “Hello A!”.

Here’s the link.

Basically, there are only three steps to take when making a custom pipe.

The First Step: Add the pipe in a new file.

In the root of the Stackblitz default Angular app, let’s add a new file and call it trim-str2.pipe.ts. Then we’ll add the following code:

1
2
3
4
5
6
7
8
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'trimStr2'})
export class TrimStrTwo implements PipeTransform {
  transform(str: string): string {
    const takeFirst1 = str.substring(0,1);
    return takeFirst1;
  }
}

The Second Step: Import the pipe into the appropriate module.

Since the starter Stackblitz Angular app only has a single module (app.module.ts), that’s where we’ll import the pipe, like this:

import { TrimStrTwo } from './trim-str2.pipe';

Now we just need to add it to the list of declarations:

declarations: [ AppComponent, HelloComponent, TrimStrTwo ],

Step 3: Use the pipe as needed

Here, we’ll be using it to trim the word “Angular”, so that only the first letter is shown.

We need to update this line of code in hello.component.ts:

template: `<h1>Hello {{ name }}!</h1>`,

The update is just a simple addition of our custom pipe:

template: `<h1>Hello {{ name | trimStr2 }}!</h1>`,

There you have it! That’s all that it takes.

Feel free to check out my work here: