Custom Filter Pipe In Angular
In this article, we will learn how to add custom filter pipe in an angular application. Angular's pipes are a very helpful feature. They offer a straightforward method for transforming our data into an Angular template.
So, let's start with the implementation
First, we need to create a new angular application using the following command in the terminal.
ng new filter-pipe-angular
Now, we need create a typescript(.ts) file for filter-pipe.pipe.ts and add the following code .
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); }); } }
Now, we need to add FilterPipe into the app.module.ts file using the following code.
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, add the following code under the app.component.ts file.
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"; }
Now, using the following code adds the owl-carousel component under the app.component.html file.
<li *ngFor="let name of userList | filter : includeText"> {{name}} </li>
Now, run the application using the ng serve command into the terminal and see the browser screen we are able to filtered records of data which contains "User" as text in it.
Conclusion
In this article, we learned how to add custom filter pipe in an angular application.
I hope this article helps you and you will like it.👍
Please give your valuable feedback and comments or suggestion in the comment section
If you have any doubt or confusion then free to ask in the comment section.