Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Filter pipe in angular

Suggested Videos
Part 44 - Angular required route parameter vs optional route parameter | Text | Slides
Part 45 - Angular form reset | Text | Slides
Part 46 - Javascript objects and reference variables | Text | Slides

In this video we will discuss implementing a filter pipe in Angular. Angular team recommends not to use pipes to filter and sort data. This is because a filtering and sorting pipe can significantly impact the performance of the application if not implemented carefully. To better understand the performance implications, let's implement a custom pipe to filter data. We discussed creating custom pipes in detail in Part 19 of Angular 2 tutorial.


We want to include Search by Name textbox on ListEmployeesComponent
filter pipe in angular


list-employees.component.html

<div class="form-group">
    <input type="text" class="form-control" placeholder="Search By Name"
            style="width:300px" [(ngModel)]="searchTerm" />
</div>
<div *ngFor="let employee of employees | employeeFilter:searchTerm">
    <div (click)="onClick(employee.id)" class="pointerCursor">
        <app-display-employee [employee]="employee" #childComponent>
        </app-display-employee>
    </div>
</div>

In list-employees.component.ts file, include the following searchTerm property

searchTerm: string;

employee-filter.pipe.ts

import { PipeTransform, Pipe } from '@angular/core';
import { Employee } from '../models/employee.model';

@Pipe({
    name: 'employeeFilter'
})
export class EmployeeFilterPipe implements PipeTransform {
    transform(employees: Employee[], searchTerm: string): Employee[] {
        if (!employees || !searchTerm) {
            return employees;
        }

        return employees.filter(employee =>
            employee.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1);
    }
}

Also do not forget to register EmployeeFilterPipe in a module.

As you can see we implemented filtering using a pipe and everything seems to be working fine. So the question that comes to our mind is,

Why did the Angular team recommend not to use pipes to filter and sort data

Well, that's because a filtering and sorting pipe can significantly impact the performance of the application. 

We will discuss these performance implications and the recommended approach to filter and sort data in our next video.

angular crud tutorial

4 comments:

It would be great if you can help share these free resources