how to filter in data in angular code example

Example 1: angular filter ngfor

// 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:

// In your .html:
<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 { }

Example 2: best way to filter table in angular

@Pipe({
   name: 'tableFilter'
})
export class TableFilterPipe implements PipeTransform {

   transform(list: any[], value: string) {

      // If there's a value passed (male or female) it will filter the list otherwise it will return the original unfiltered list. 
      return value ? list.filter(item => item.gender === value) : list;

   }
}

Tags:

Misc Example