【问题标题】:How do I make a pipe dynamic angular2如何使管道动态angular2
【发布时间】:2017-02-09 15:36:09
【问题描述】:

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

我想使用来自ngx-pipes (https://github.com/danrevah/ngx-pipes) 的filterBy 来过滤我的数据。

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

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

  1. 我想分配一个变量“currentCategory”而不是“Bar Tech”作为“硬编码”过滤器 - 我该怎么做?我是否只需将Bar Tech 替换为currentCategory

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

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

【问题讨论】:

    标签: angular angular-pipe


    【解决方案1】:

    1st.:是的。

    2nd.:您应该在component 中导入pipe 并在按钮(click) 上调用.transform() 事件

    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"...
    

    【讨论】:

    • 你能解释一下onClickBtn吗?这是你决定的名字,还是..?
    • 这只是一个假名..你可以随便命名。
    • 我可以通过这个函数将 currentCategory 传递给我的 (click)="" 事件,对吗?
    • 是的,你可以..(click)="YOUR_FUNCTION_NAME(currentCategory)".
    • 这并没有改变我点击时的显示数据:(
    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 2017-08-25
    • 2016-08-28
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多