2017-04-10 59 views
0

我想使用管道過濾表。 這是我的過濾器的代碼。使用輸入框過濾角度2表

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> 

代碼當我嘗試查看網頁,我有在瀏覽器中出現這個錯誤:「無法讀取未定義的屬性'0'。」由於過濾器,頁面不想加載。我的猜測是,由於filterItem最初是空的,這會阻止頁面加載。但我不知道如何解決它。 任何幫助將不勝感激!謝謝!

+0

貌似'args'是不定值這裏,也許你可以更新您的過濾器,只運行,如果'args'被定義爲先前存在根本不需要運行濾波器。 – GillesC

回答

1

我的猜測是,由於filterItem最初是空的,這可以防止頁面加載 。

實際上它是undefined

這個問題可以固定執行以下操作:

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

工程就像一個魅力。謝謝! – edkeveked