如何使管道动态 angular2
How do I make a pipe dynamic angular2
我有以下 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' }}
而不是 'Bar Tech' 作为 'hard coded' 过滤器,我想分配一个变量 'currentCategory' - 我该怎么做?我只是将 Bar Tech
替换为 currentCategory
吗?
如何在单击按钮时更新管道?我知道我可以绑定一个 (click) 事件,但是我不太确定如何通过 (click) 更新 currentCategory
,这会提示管道再次过滤。
换句话说:使用按钮,我想根据匹配的 属性 更新我显示的数据(按钮的值必须在对象的 属性 中)
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"...
我有以下 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' }}
而不是 'Bar Tech' 作为 'hard coded' 过滤器,我想分配一个变量 'currentCategory' - 我该怎么做?我只是将
Bar Tech
替换为currentCategory
吗?如何在单击按钮时更新管道?我知道我可以绑定一个 (click) 事件,但是我不太确定如何通过 (click) 更新
currentCategory
,这会提示管道再次过滤。
换句话说:使用按钮,我想根据匹配的 属性 更新我显示的数据(按钮的值必须在对象的 属性 中)
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"...