2017-05-06 59 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); 
    }); 
    } 

} 

它仅适用于一个说法我怎么能与一个输入过滤任何表列(现在只过滤名称列)?

有我的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(术语);'?但请阅读https://angular.io/docs/ts/latest/guide/pipes.html#!#appendix-no-filterpipe-or-orderbypipe- –

回答

1

您可以通过所有属性中alias使用Object.keys()搜索:

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的评论是点上 - 你可能不希望这样做在管道中。将该逻辑移入组件类更好。