自定义管道更多参数

时间:2017-05-06 14:53:05

标签: angular

我正在尝试自定义管道,它将从表中过滤数据。

我是这样做的:

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>

1 个答案:

答案 0 :(得分: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的评论很明显 - 你可能不想在管道中这样做。将该逻辑移动到组件类中会好得多。