如何编写Angular ngFor管道以按对象属性过滤对象数组? [英] How can I write an Angular ngFor pipe to filter array of objects by object property?
本文介绍了如何编写Angular ngFor管道以按对象属性过滤对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个选择。
一个用于联盟
,一个用于部门
我想创建一个管道
来过滤部门
取决于选择的是 League
。
I want to create a Pipe
that will filter Divisions
depending on what League
is selected.
提供以下数据。如果我选择 Random Beer League
仅 TwoFour
和 SixPack
显示为部门
选择的选项。
Giving the data below. If I select Random Beer League
only TwoFour
and SixPack
should show up as options for the Divisions
select.
leagues = [
{id: 1, leagueName: 'Recreation League' },
{id: 2, leagueName: 'Random Beer League' }
];
divisions = [
{id: 1, divisionName: 'SoGreen', leagueId: 1, leagueName: 'Recreation League' },
{id: 2, divisionName: 'Yellow', leagueId: 1, leagueName: 'Recreation League' },
{id: 3, divisionName: 'TwoFour', leagueId: 2, leagueName: 'Random Beer League' },
{id: 4, divisionName: 'SixPack', leagueId: 2, leagueName: 'Random Beer League' }
];
*请注意-插件中的数据是硬编码的,但在我的应用程序设置中它是可观察的。
*Note - data in plunker is hard coded but in my app setup its Observable.
推荐答案
我创建了一个自定义管道,并使用它来过滤除法下拉列表。
I have create a custom pipe and used it to filter division dropdown.
@Pipe({
name: 'myfilter',
pure: false
})
export class MyFilterPipe implements PipeTransform {
transform(items: any[], args: any[]): any {
return items.filter(item => item.leagueName.indexOf(args.leagueName) > -1);
}
}
<option *ngFor="let division of divisions | myfilter:leagueSelected" [ngValue]="division">{{division.divisionName}}</option>
请查看此 Plnkr
这篇关于如何编写Angular ngFor管道以按对象属性过滤对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文