使用输入框过滤角度2表

时间:2017-04-10 14:37:24

标签: javascript angular

我正在尝试使用管道过滤表格。 这是我的过滤器的代码。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'myFilter'
})
export class MyFilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return value.filter(item => item.name.indexOf(args[0]) !== -1);
  }
}

我在app.module.ts

中导入了过滤器
    import { MyFilterPipe } from './common/my-filter.pipe';
    @NgModule({
  declarations: [
    MyFilterPipe
  ],

这是我的视图HTML

的代码
<md-input-container>
    <md-icon>search</md-icon>
    <input mdInput placeholder="Favorite food"  [(ngModel)]="filterItem">
   </md-input-container> 
... 
<table>
<tr *ngFor="let item of items | myFilter: filterItem">
    <td>
      <a  href="#">
         <span >
         {{item.name}}
         </span>
      </a>
    </td>
    <td>
        <div>{{item.value1}}</div>
      <div>{{item.value2}}</div>
    </td>
    <td>
        <span >
         item.description
        </span>
    </td>
  </tr>
</table>

当我尝试查看该页面时,我在浏览器中出现此错误:&#34;无法读取属性&#39; 0&#39;未定义的。&#34;由于过滤器,页面不想加载。我的猜测是,由于filterItem最初为空,这会阻止页面加载。但我不知道如何解决它。 任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

  

我的猜测是,由于filterItem最初为空,这可以防止   要加载的页面。

实际上它是未定义

可以解决以下问题:

transform(value: any, args?: any): any {
  return !!args ? value.filter(item => item.name.indexOf(args[0]) !== -1) : value;
}