Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply filters to *ngFor?

Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, with no clear documentation.

Namely what I'm trying to achieve could be viewed from the following perspective

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div> 

How to implement so using pipes?

like image 279
Khaled Avatar asked Dec 08 '15 19:12

Khaled


1 Answers

Basically, you write a pipe which you can then use in the *ngFor directive.

In your component:

filterargs = {title: 'hello'}; items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}]; 

In your template, you can pass string, number or object to your pipe to use to filter on:

<li *ngFor="let item of items | myfilter:filterargs"> 

In your pipe:

import { Pipe, PipeTransform } from '@angular/core';  @Pipe({     name: 'myfilter',     pure: false }) export class MyFilterPipe implements PipeTransform {     transform(items: any[], filter: Object): any {         if (!items || !filter) {             return items;         }         // filter items array, items which match and return true will be         // kept, false will be filtered out         return items.filter(item => item.title.indexOf(filter.title) !== -1);     } } 

Remember to register your pipe in app.module.ts; you no longer need to register the pipes in your @Component

import { MyFilterPipe } from './shared/pipes/my-filter.pipe';  @NgModule({     imports: [         ..     ],     declarations: [         MyFilterPipe,     ],     providers: [         ..     ],     bootstrap: [AppComponent] }) export class AppModule { } 

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.

like image 78
phuc77 Avatar answered Sep 21 '22 00:09

phuc77