Angular 2 Pipe to filter array of strings with provided search string

In This Article, we will create a new Pipe for filtering array of strings with provided search/filter string.

Prerequisites:

Fire up your Visual Code and inside the terminal create a new Angular project.

ng new searchPipeProject

ng new searchPipeProject

npm might take a while to install packages.

Once your project is setup, let’s add a new pipe using angular-cli.  Note: if you are like me, you would want to properly organize your code structure. If you create a new pipe from the root of the project, it will be created in the root directory. Fortunately, angular-cli takes relative paths into account when creating a new component. So create a new folder called “pipes” under the root(app) folder. Browse to that folder and create a new pipe.

ng generate pipe searchTxtAry

ng generate pipe searchTxtAry

Blow is how the final code will look like. We will go through it soon.

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

@Pipe({
name: 'searchText'
})
export class SearchTextPipe implements PipeTransform {

transform(value: any, q: string): any {
if (!q) {
return value;
}

if (q === '') {
return value;
}
console.log(q);

return value.filter(function (w) {
return w.indexOf(q) > 0;
});

}
}

The core function here is “transform”, it takes two arguments, the value is the type of “any” and it will be out array on which pipe is applied. q is the search Text which we will be passing to the pipe as a parameter( we will soon see how).

We basically use two javascript functions.

Filter: filters out all the array elements that matches a function. More at MDN

IndexOf: returns the index of searched text, -1 if not found. More at MDN.

So in a nutshell, filter out all the array elements what have the string we are searching for.

Let’s see it in action. Modify the app.component.html and app.component.ts in your project as below:

app.component.ts

import { SearchTxtAryPipe } from './pipes/search-txt-ary.pipe';
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
names = ['Gelya McMaster', 'Maxwell Irwin', 'Johannes McMaster', 'Davon Irwin'];
searchtxt: '';
}

app.component.html

<div>
<input name="search" id="search" type="text" [(ngModel)]="searchtxt" #s="ngModel">
</div>

<div>

<ul>

<li *ngFor="let n of names | searchTxtAry: searchtxt">
{{n}}
</li>

</ul>

</div>

Also, don’t forget to add FormModule in import inside app.module.ts

@NgModule({
declarations: [
AppComponent,
<strong>SearchTxtAryPipe</strong>
],
imports: [
BrowserModule,
<strong>FormsModule</strong>
],
providers: [],
bootstrap: [AppComponent]
})

App in Action:

 

You can find the complete source code at GitHub