如何编写 Angular ngFor 管道以按对象 属性 过滤对象数组?
How can I write an Angular ngFor pipe to filter array of objects by object property?
我有 2 个 select。
一个用于 Leagues
一个用于 Divisions
我想创建一个 Pipe
来过滤 Divisions
取决于 League
是什么 selected。
提供以下数据。如果我 select Random Beer League
只有 TwoFour
和 SixPack
应该显示为 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' }
];
*注意 - plunker 中的数据是硬编码的,但在我的应用程序中设置了它的 Observable。
我已经创建了一个自定义管道并用它来过滤分区下拉列表。
@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
我有 2 个 select。
一个用于 Leagues
一个用于 Divisions
我想创建一个 Pipe
来过滤 Divisions
取决于 League
是什么 selected。
提供以下数据。如果我 select Random Beer League
只有 TwoFour
和 SixPack
应该显示为 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' }
];
*注意 - plunker 中的数据是硬编码的,但在我的应用程序中设置了它的 Observable。
我已经创建了一个自定义管道并用它来过滤分区下拉列表。
@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