2017-05-06 8 views
1

テーブルからデータをフィルタリングするカスタムパイプを実行しようとしています。カスタムパイプ多くの引数

私はこのようにそれをやった:

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

@Pipe({ 
    name: 'filter' 
}) 
export class FilterPipe implements PipeTransform { 

    transform(employees: any, term: any): any { 
    // check if search term is undefined 
    if (term === undefined) return employees; 
    // return updated array 
    return employees.filter(function(alias){ 
     return alias.name.includes(term); 
    }); 
    } 

} 

それは私が1つの入力(今は名前だけの列をフィルタリング)で任意のテーブルの列をフィルタリングすることができますどのように一つの引数でのみ動作しますか?

私のhtml

<div class="container-fluid"> 
    <div class="col-4"> 
     <!-- filter --> 
     <form id="filter"> 
      <label>Search:</label> 
      <input type="text" [(ngModel)]="term" name="filter"> 
     </form> 
     <!-- end --> 
     <br> 
     <table class="table table-striped"> 
      <thead> 
       <tr> 
        <th>Name</th> 
        <th>Dept</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr *ngFor="let alias of employees | filter:term"> 
        <td>{{ alias.name }}</td> 
        <td>{{ alias.dept }}</td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
</div> 
+2

'return alias.name.includes(term)|| alias.dept.includes(term); '?しかし、https://angular.io/docs/ts/latest/guide/pipes.html#!#appendix-no-filterpipe-or-orderbypipe- –

答えて

1

あなたはObject.keys()を使用してalias内のすべてのプロパティを検索することができますがあります。

return employees.filter(function(alias) { 
    let found = false; 
    Object.keys(alias).forEach(function(key) { 
     found = found || alias[key].includes(term); 
    }); 
    return found; 
}); 

それとも、これは矢印機能=>reduce()で、より簡潔に表現することができます。

return employees.filter(alias => 
    Object.keys(alias).reduce(
     (found, key) => found || alias[key].includes(term), false 
    ) 
); 

あるいはさらに良いObject.values()と(しかしbrowser supportは、現在のように良くありませんので、あなたがpolyfillにそれを必要とします):

return employees.filter(alias => 
    Object.values(alias).reduce(
     (found, value) => found || value.includes(term), false 
    ) 
); 

しかしJBNizetさんのコメントは、上のスポットです@ - あなたはおそらくこれを行うにはしたくありませんパイプでそのロジックをコンポーネントクラスに移す方がずっと優れています。

関連する問題