I have created a custom pipe for my project and included my pipe file in my module in the declartions array.
search-user.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import {
User
} from './user';
@Pipe({
name: 'searchUser'
})
export class SearchUserPipe implements PipeTransform {
constructor() {
console.log('imported');
}
transform(items: User[], filter: User): User[] {
console.log('inside transform');
if (!items || !filter) {
return items;
}
return items.filter((item: User) => this.applyFilter(item, filter));
}
applyFilter(user: User, filter: User): boolean {
for (const field in filter) {
if (filter[field]) {
if (typeof filter[field] === 'string') {
if (user[field].toLowerCase().indexOf(filter[field].toLowerCase()) === -1) {
return false;
}
} else if (typeof filter[field] === 'number') {
if (user[field] !== filter[field]) {
return false;
}
}
}
}
return true;
}
}
My user model which i have used in pipe.ts
export class User {
studentId: Number;
name: String;
email: String;
phoneNumber: String;
}
This is my html file in which i need to sort the data using the pipe
<div *ngIf="dataLoaded" class="table-responsive">
<table #myTable class="table">
<thead>
<tr>
<th><input type="text" name="title" [(ngModel)]="filter.studentId" placeholder="ID"></th>
<th><input type="text" name="title" [(ngModel)]="filter.name" placeholder="NAME"></th>
<th><input type="text" name="title" [(ngModel)]="filter.email" placeholder="EMAIL"></th>
<th><input type="text" name="title" [(ngModel)]="filter.phoneNumber" placeholder="PHONE NUMBER"></th>
</tr>
</thead>
<tbody>
<tr id={{i}} *ngFor="let user of userDetails;let i of index | searchUser: filter">
<td>{{user.studentId}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.phoneNumber}}</td>
</tr>
</tbody>
</table>
</div>
I am trying to create filter for the every column of the table. I have also checked if my pipe file is imported in my bundle by logging something into the constructor of the file.
I am stuck here the pipe is not working for any of the fields.
I think you are using wrong syntax ngFor in your html. Try this
*ngFor="let user of userDetails | searchUser: filter; index as i;">