How can I write an Angular ngFor channel to filter an array of objects by an object property?

I have 2 choices.

One for Leaguesand one forDivisions

I want to create Pipeone that will filter Divisionsbased on what is selected League.

Providing data below. If I choose Random Beer League, only TwoFour, and SixPackshould be displayed as options for Divisions.

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 to show the setting

* Note. The data in plunker is hardcoded, but in my application setup its observable.

+4
source share
1 answer

I created my own channel and used it to filter the drop-down list.

@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

+5

Source: https://habr.com/ru/post/1666564/


All Articles