Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have 2 selects.

One for Leagues and one for Divisions

I want to create a Pipe that will filter Divisions depending on what League is selected.

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' }
];

PLUNKER to show the setup

*Note - data in plunker is hard coded but in my app setup its Observable.

like image 854
locnguyen Avatar asked Jan 12 '17 00:01

locnguyen


People also ask

Can we apply pipe in ngFor?

Basically, you write a pipe which you can then use in the *ngFor directive. Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results. Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.

Can we use ngFor for object?

You use the *ngFor directive to traverse over an array object and display the data in the UI.


1 Answers

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>

Please look into this Plnkr

like image 91
Hardik Patel Avatar answered Oct 17 '22 02:10

Hardik Patel