I'm beginner to Angular 2. I was trying to create the custom pipe for search operation in angular 2. While trying to filter the objects of data by using the filter function I was getting as like my data is not supporting the filter function.
My Pipe code :
import {Pipe,PipeTransform} from '@angular/core'
@Pipe({
name : 'GenderSetter'
})
export class SettingGenderPipe implements PipeTransform
{
transform(Employees:any,EmpFind:any):any{
if(EmpFind === undefined) return Employees;
else {
return Employees.filter(function(x){
console.log(x.toLowerCase().includes(EmpFind.toLowerCase()));
return x.toLowerCase().includes(EmpFind.toLowerCase())
})
}
}
}
My template html file :
<div style="text-align:center">
<input type="text" id='txtsearch' [(ngModel)]="EmpFind"/>
<table>
<thead>
<td>Name</td>
<td>Gender</td>
<td>Salary</td>
</thead>
<tbody>
<tr *ngFor='let x of Employees'>
<td>{{x.Empname | GenderSetter : EmpFind}}</td>
<td>{{x.gender}}</td>
<td>{{x.salary}}</td>
</tr>
</tbody>
</table>
</div>
My Component Code :
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
Employees=[
{Empname : 'Roshan',gender:1,salary:'70k' },
{Empname : 'Ishita',gender:0,salary:'60k' },
{Empname : 'Ritika',gender:0,salary:'50k' },
{Empname : 'Girish',gender:1,salary:'40k' },
]
}
In the console I'm getting the error as : ERROR TypeError: Employees.filter is not a function.
The problem is that you are applying the pipe to the x.Empname, however the pipe itself should accept an array. Move your pipe to the ngFor:
<tr *ngFor='let x of Employees | GenderSetter : EmpFind'>
<td>{{x.Empname}}</td>
<td>{{x.gender}}</td>
<td>{{x.salary}}</td>
</tr>