Custom Pipe in Angular 4

We need to add filter with our data. So, there we need to create custom pipe.

–TS File (filter.pipe.ts)

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {
  transform(servers: any, term: any): any {
    //check if search term is undefined
    if (term === undefined) return servers;
    //return updated ninjas array
    return servers.filter(function(server){
      return server.name.toLowerCase().includes(term.toLowerCase());
    });
  }
}

register pipe in module.ts file

import { FilterPipe } from "../shared/filter.pipe";

@NgModule({
  declarations: [
    FilterPipe
  ],
})

–HTML File (user.component)

<div class="form-group">
<input class="form-control"type="text"placeholder="Filter" [(ngModel)]="term">
</div>
<table class="table">
<thead>
<th>Name</th>
<th>Joining Date</th>
<th>Age</th>
</thead>
<tbody>
<tr *ngFor="let user of list | filter:term">
<td>{{user.name}}</td>
<td>{{user.joining_date}}</td>
<td>{{user.age}}</td>
</tr>
</tbody>
</table>

Leave a Reply

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