How to Use Custom Pipes in Angular

Here, we will learn about how we can implement our own custom pipes in Angular.

Pipes are very useful features in Angular. They are simple way to transform our data in an Angular template.

The CurrencyPipe is the very basic example which transforms a given number into a currency string. The CurrencyPipes is one of several examples of Angular Pipes provided by the Angular Framework. In addition to this built-in pipes, we can create our own pipes also.

Prerequisites:

  • Basic knowledge of Angular

We will create a filter pipe in Angular in which we can get the list of data which includes the particular string in the array.

Create a TS file as filter-pipe.pipe.ts and add the following code in it.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filter'
})
export class FilterPipe implements PipeTransform {

    transform(items: any[], text: string): any[] {

        if (!items) { return []; }

        if (!text) { return items; }

        text = text.toLowerCase();
        return items.filter(x => {
            return x.toLowerCase().includes(text);
        });
    }
}

Filter pipe will take an array as input and returns the filtered array based on the search query we have passed in it.

Now, you need to import the filter pipe in our app.module.ts file in the declarations section like this.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FilterPipe } from './filter-pipe.pipe';

@NgModule({
  declarations: [
    AppComponent,
    FilterPipe
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, open the app.component.ts file and add the following code in it.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'custom-pipes-in-angular';
  userList: any = ["User 1", "User 2", "User 3", "User 4", "User 5", "User 6", "Test", "TT"];
  includeText = "User";
}

We will now use the filter in our HTML Template and we will get the list of data which includes User as text in it.

<li *ngFor="let name of userList | filter : includeText">
  {{name}}
</li>

filter : includeText, we have use it like this to filter the users list.

Output:

custom-pipe-in-angular

That’s it. Let me know if you face any difficulties.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories