问题
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' }}
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
withcurrentCategory
?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