Categories
Uncategorized

Parameterized Pipes for input search in Angular (custom filters)

Lets say we want to filter through a list of jobs that look like the following using an Angular 4.4.5 setup.

job-state.ts

export interface JobState {
    id: number;
    title: string;
    company: string;
    city: string;
    state: string;
    zip: number;
}

jobs filter

We need to create a custom pipe that takes in the search term as an input parameter for this.

search-jobs.pipe.ts

import {Pipe, PipeTransform} from '@angular/core';

import {JobState} from './job-state';

@Pipe({
    name: 'searchJobs'
})
export class SearchJobsPipe implements PipeTransform {
    transform(jobs: JobState[], searchText: string): any[] {
        if (!jobs) {
            return [];
        }
        if (!searchText) {
            return jobs;
        }
        searchText = searchText.toLowerCase();
        return jobs.filter(it => {
            return it.title.toLowerCase().includes(searchText) ||
                it.company.toLowerCase().includes(searchText) || it.city.toLowerCase().includes(searchText) ||
                it.state.toLowerCase().includes(searchText) || it.zip.toString().toLowerCase().includes(searchText);
        });
    }
}

app.module.ts

Now add this app.module.ts to the Declarations part of NgModule, after including the AppComponent where you wish to use this.

// ...

import {AppComponent} from './app.component';
import {SearchJobsPipe} from './search-jobs.pipe';

@NgModule({
    //
     ...

     declarations: [ AppComponent,
                    SearchJobsPipe 
                  ],

    // ....
}]

app.component.ts

Make sure you have app.component.ts that is somewhat similar to the base structure here.

import { Component, OnInit } from '@angular/core';
import {JobState} from './job-state';

@Component({
  selector: 'app-app1',
  templateUrl: './app1.component.html',
  styleUrls: ['./app1.component.scss']
})
export class App1Component implements OnInit {
  jobSearch = '';
  jobs: JobState[];

  constructor() { }

  ngOnInit() {
     this.getJobs();
  }

  getJobs(): void {
  // Make API call here and load the jobs on success 
  // this.jobs = response.data;
  }

}

app.component.html

Now add the following code into your app.component.html file or your components template.



{{job.title}} - {{job.company}}
{{job.city}}, {{job.state}} - {{job.zip}}