Table Search Filter In Angular
In this article, we will how to add table search filter in angular application. In today's applications and websites, searching is a key feature that is frequently used. We may see many different examples of applications, such as Google Maps for finding locations and the Play Store or App Store for searching software.
So, let's start with the implementation
First, we need to create a new angular application using the following command in the terminal.
ng new angular-table-search
Now, we need to install ng2-search-filter npm packages using the following command in the terminal.
npm install ng2-search-filter
Now, add the Ng2SearchPipeModule module in the app.module.ts file using the following code.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; // search module import { Ng2SearchPipeModule } from 'ng2-search-filter'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, Ng2SearchPipeModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Now, add the following code under the app.component.ts file.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { searchText; products = [ { id: 1, name: 'Smartphone' }, { id: 2, name: 'Headphone' }, { id: 3, name: 'Bike' }, { id: 4, name: 'Laptop' }, { id: 5, name: 'TV' }, { id: 6, name: 'PC' }, { id: 7, name: 'Car' } ]; }
Now, add the following code under the app.component.html file.
<input [(ngModel)]="searchText" placeholder="Enter Product ID/Name" /> <br/><br/> <table width="15%" border="1"> <thead> <tr> <th>Id</th> <th>Product Name</th> </tr> </thead> <tbody> <tr *ngFor="let product of products | filter:searchText"> <td>{{product.id}}</td> <td>{{product.name}}</td> </tr> </tbody> </table>
Now, run the application using the ng serve command into the terminal and see the browser screen, now we are able easily filter specific data into the table.
Conclusion
In this article, we learned how to add table search filter in angular application using the ng2-search-filter packages.
I hope this article helps you and you will like it.👍
Please give your valuable feedback and comments or suggestion in the comment section
If you have any doubt or confusion then free to ask in the comment section.