How to create search filter functionality in angular

Share the post

Hello All, In the last angular tutorial we had discussed How to create pdf viewer in angular. Now, In this angular tutorial, we will learn how to create search filter functionality in angular applications in detail with the help of an example. In this example, we are going to use the npm package ng2-search-filter.

Nowadays, Modern web applications must have search functionality that gives a nice user experience to customers. ng2-search-filter gives that functionality which is really useful to search queries & get expected results.

Now, let’s start to create a search filter in our angular application.

Step1: Create angular project

Create a new angular project using the following command.

ng new <APPNAME>



Now, move to our root project directory using the following command

cd <APPNAME>



Open the newly created angular project in Visual Studio Code. Use the following command to open the project.

code .



Step2: Install ng2-search-filter NPM package

It’s time to install ng2-search-filter Open the terminal & write the below command

npm i ng2-search-filter --save



Step3: Import Ng2SearchPipeModule

Now, Import the Ng2SearchPipeModule in app.module.ts as shown below.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { FormsModule } from '@angular/forms';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    Ng2SearchPipeModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step4: HTML, TS Code

Write HTML code in app.component.html as follows

<div>
    <input type="text" [(ngModel)]="searchTerm">
    <div *ngFor="let item of items | filter:searchTerm">
        <p>
            {{item.name}}
        </p>
    </div>

</div>



Now, Write the logic in app.component.ts as shown below

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'angular-pdf-viewer';
  searchTerm: string;



  constructor() {

  }

  items = [{ id: 1, name: "Ramesh" }, { id: 2, name: "Suresh" }, { id: 3, name: "Dinesh" }];
}

Now, let’s see the output. It will filter our search results as expected.

Step5: Output

output
Output

1 thought on “How to create search filter functionality in angular”

Leave a Comment