簡體   English   中英

過濾器不是自定義管道角度2中的功能

[英]Filter is not a function in custom pipe angular 2

我是Angular 2的初學者。我試圖為angular 2中的搜索操作創建自定義管道,同時嘗試通過使用過濾器功能過濾數據對象,就像我的數據不支持過濾器功能一樣。

我的管道代碼:

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())
      })
    }    
   }   
}

我的模板html文件:

<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>

我的組件代碼:

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' },
]
}

在控制台中,我得到的錯誤為:錯誤TypeError:Employees.filter不是函數。

問題是您將管道應用到x.Empname,但是管道本身應該接受一個數組。 將管道移至ngFor:

  <tr *ngFor='let x of Employees | GenderSetter : EmpFind'>
        <td>{{x.Empname}}</td>
        <td>{{x.gender}}</td>
        <td>{{x.salary}}</td>
  </tr>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM