How do I make a pipe dynamic angular2

只愿长相守 提交于 2019-12-10 17:09:09

问题


I have the following UI buttons:
[Show All] [Category 1] [Category 2]

I would like to use filterBy from ngx-pipes (https://github.com/danrevah/ngx-pipes) to filter my data.

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

From the docs, their example is: {{ users | filterBy: ['work.company']: 'Bar Tech' }}

  1. Instead of 'Bar Tech' being a 'hard coded' filter, I would like to assign a variable 'currentCategory' instead - how do I do that? Do I simply replace Bar Tech with currentCategory?

  2. How do I make the pipe update on button click? I understand I can bind a (click) event, however I am not quite sure how to update currentCategory though the (click) which would prompt the pipe to filter again.

In other words: Using buttons, I would like to update my displayed data based on a matching property (button's value must be in object's property)


回答1:


1st.: Yes.

2nd.: You should import the pipe inside your component and call .transform() on button (click) event.

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
    );
  }
}

Remember to change the source array in your template, you should use:

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


来源:https://stackoverflow.com/questions/42140805/how-do-i-make-a-pipe-dynamic-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!