Blog>
Snippets

Developing a Custom Data Filter Pipe

Illustrate the creation of a standalone Angular pipe for filtering data arrays, usable across different components.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customFilter'
})
export class CustomFilterPipe implements PipeTransform {
  transform(items: any[], filter: {[key: string]: any }): any[] {
    if (!items || !filter) {
      return items;
    }

    return items.filter(item => {
      for (let field in filter) {
        if (item[field] === undefined) {
          return false;
        }

        const type = typeof item[field];
        const isMatching = (
          type === 'string'
            ? item[field].toLowerCase().indexOf(filter[field].toLowerCase()) !== -1
            : item[field] === filter[field]
        );

        if (!isMatching) {
          return false;
        }
      }
      return true;
    });
  }
}
This is an Angular pipe called 'customFilter' that implements the PipeTransform interface. It takes an array of items and a filter object as parameters. The transform function then filters the items array based on the filter criteria provided. If the item's field matches the filter's criteria, it is included in the result, otherwise, it's excluded. The filter works for both string and non-string types, using a case-insensitive comparison for strings.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CustomFilterPipe } from './custom-filter.pipe';

@NgModule({
  declarations: [
    AppComponent,
    CustomFilterPipe
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
This is the NgModule where the CustomFilterPipe is declared. The AppModule registers the pipe so that it can be used throughout this Angular module. The declarations array is updated to include the CustomFilterPipe, making it available for use in any component within the AppModule.