Moshe
Moshe

Reputation: 2674

How do I make a pipe dynamic angular2

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)

Upvotes: 4

Views: 1869

Answers (1)

developer033
developer033

Reputation: 24894

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

Upvotes: 4

Related Questions