如何制作管道动态angular2

时间:2017-02-09 15:36:10

标签: angular angular-pipe

我有以下UI按钮:
[显示全部] [类别1] [类别2]

我想使用filterByhttps://github.com/danrevah/ngx-pipes)中的ngx-pipes来过滤我的数据。

Usage: array | filterBy: [prop, nested.prop, ...]: search: [strict | optional]

从文档中,他们的示例是:{{ users | filterBy: ['work.company']: 'Bar Tech' }}

  1. 我不想将“Bar Tech”作为“硬编码”过滤器,而是指定一个变量'currentCategory' - 我该怎么做?我只是将Bar Tech替换为currentCategory吗?

  2. 如何在按钮点击时更新管道?我知道我可以绑定一个(点击)事件,但我不太确定如何通过(点击)更新currentCategory,这会提示管道再次过滤。

  3. 换句话说:使用按钮,我想根据匹配的属性更新我显示的数据(按钮的值必须在对象的属性中)

1 个答案:

答案 0 :(得分:4)

1st。:是的。

第二。:您应该在pipe内导入component并在按钮.transform() 事件上致电(click) >

import { FilterByPipe } from 'ngx-pipes/src/app/pipes/array/filter-by';

@Component({
  // ...
  providers: [FilterByPipe]
})
export class AppComponent {

  filteredArr: any[]; // your correct type   

  constructor(private readonly filterByPipe: FilterByPipe) {
    // ...
    this.filteredArr = this.users.slice(); // clone array by value (not by reference)
  }

  onClickBtn() {
    this.filteredArr = this.filterByPipe.transform(
      this.users, 
      'work.company',
      this.currentCategory
    );
  }
}

请记住更改template中的源数组,您应该使用:

*ngFor="let <variable> of filteredArr"...