简体   繁体   中英

Filter is not a function in custom pipe angular 2

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM