Creating a search filter in Angular is a common requirement for many applications, especially when dealing with large datasets. This report will guide you through the process of implementing a search filter in Angular, covering various methods and best practices.
In a real application, we might have a large list of data that we have displayed through a table using pagination but it would make users inconvenienced and time-taking to search for any particular keyword in a long list without any search functionality provided. We can solve the above issues by providing users with input searches, where users can filter the data based on the user requirements. We need to implement an Angular search filter to array objects in the input text field.
Table of Contents
How to implement an Angular search filter?
A search filter is a powerful tool that enables users to filter data based on specific criteria, thereby making it easier to locate pertinent information within a large dataset. In Angular, this functionality can be implemented using pipes, directives, and RxJS operators. Additionally, optimizing your Angular application for search engines is essential for enhancing its visibility and discoverability.
We can implement an Angular search filter using our own custom filter pipe or we can use a third-party search filter library like ng2-search-filter. The ng2-search-filter library is open source and it allowing us to make custom search filters but this library had not update from last 4 years. We can easily implement search filter without using any third parites. If you are using Angular material bootstrap, or any other UI frameworks, the best approach is to check if any available search filter on the framework.
Different ways to implement Angular search filter
Here we have listed different approaches to implementing Angular search filters.
Name of Angular search filter | Description | |
Angular bootstrap table search filter | If you are using Bootstrap for your angular project, then it is best to use the ng-bootstrap component. We have a complete tutorial on how to implement pagination and search filters on the data table using the ng-bootstrap library. Check here | |
Angular material search filter | Same as bootstrap, if you are using Angular material UI, then it is best to use its components, which are ready to use. | |
custom search filter | We can create our own search filter with help of angular pipes. |
Using Pipes for AngulaSearch Filtering
A pipe in Angular is a way to transform data within your template by accepting data input and returning a transformed version of the data as output. Pipes can be used in both HTML template expressions and components.
For example, you can use the built-in uppercase pipe in your component template to convert a string to uppercase:
Component Template:
<div>
<p>{{ myString | uppercase }}</p>
</div>
Before delving into the implementation of the Angular search filter project, we need to set up an Angular project. To get started, create our Angular project using the ng command
Let’s first create an Angular project for the Angular search filter and name the project ‘searchFilterApps’.
ng new searchFilterApps
cd searchFilterApps
All we need is dummy data so that users can search data based on filter criteria in the search input. We will add it directly to the component where we are using it.
Angular search filter example using a custom filter pipe
We can achieve an Angular search filter without using any library. Angular has lots of predefined pipes that allow us to format and transform data. Pipes are functions that we can use in template expressions to format input data before it’s rendered.
Angular has lots of its own built-in pipes and we can use pipes for synchronous and asynchronous data. Example of Angular-built pipe like lowercase.
lowercase: <pre>'{{ 'EdUpALa'| lowercase}}'</pre> //Output edupala
Here is our screenshot of Angular search filter using custom pipe.
Step 1: Create custom search pipe to filter by countries names
Angular doesn’t have a search filter pipe, so we will create our own custom search pipe to perform an Angular search filter on the input field. Let’s first create a custom pipe using the following command:
ng g pipe searchFilter
Edit the ‘search-filter.pipe.ts’ file to filter the list based on the user-typed text criteria in the input field.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'searchFilter',
standalone: true,
})
export class SearchFilterPipe implements PipeTransform {
transform(list: any[], filterText: string): any {
return list
? list.filter(
(item) => item.name.search(new RegExp(filterText, 'i')) > -1
)
: [];
}
}
Step 2: Import and Add Custom Search Filter Method in Component
To filter data using our custom filter pipe, first, we need to import it inside our component where we are using it. We also need some dummy data to perform the search filter. Let’s edit the ‘app.component.ts’ file to retrieve data. We have a search method to filter our data.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { SearchFilterPipe } from './pipes/search-filter.pipe';
interface Country {
name: string;
flag: string;
area: number;
population: number;
}
@Component({
selector: 'app-root',
standalone: true,
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
imports: [CommonModule, FormsModule, SearchFilterPipe],
})
export class AppComponent {
searchTerm = '';
filteredCountries: Country[] = [];
countries: Country[] = [
{
name: 'Russia',
flag: 'f/f3/Flag_of_Russia.svg',
area: 17075200,
population: 146989754,
},
{
name: 'France',
flag: 'c/c3/Flag_of_France.svg',
area: 640679,
population: 64979548,
},
{
name: 'Germany',
flag: 'b/ba/Flag_of_Germany.svg',
area: 357114,
population: 82114224,
},
{
name: 'Canada',
flag: 'c/cf/Flag_of_Canada.svg',
area: 9976140,
population: 36624199,
},
{
name: 'Vietnam',
flag: '2/21/Flag_of_Vietnam.svg',
area: 331212,
population: 95540800,
},
{
name: 'Mexico',
flag: 'f/fc/Flag_of_Mexico.svg',
area: 1964375,
population: 129163276,
},
{
name: 'United States',
flag: 'a/a4/Flag_of_the_United_States.svg',
area: 9629091,
population: 324459463,
},
{
name: 'India',
flag: '4/41/Flag_of_India.svg',
area: 3287263,
population: 1324171354,
},
];
search() {
this.filteredCountries = this.countries.filter((country: Country) =>
country.name.toLowerCase().includes(this.searchTerm.toLowerCase())
);
}
}
Next, implement the filter functionality when user start typing on search input. Create a method that takes a search term as a parameter and updates the filtered
Items array virables based on the search term.
Step 3: Used our custom search custom filter in component template
To use the custom pipe, you need to import it into the app module and then use it in your component’s template as below.
<someElement *ngFor="let country of countries | searchFilter: searchTerm; let i = index">
Edit the app.component.html template to add the search bar input field and our custom searchFilter pipe on the ngFor loop of the list.
<form class="wrap">
<div class="search">
<h3>Search country by name filter:</h3>
<input
class="searchTerm"
type="text"
name="searchTerm"
placeholder="Filter by country name"
[(ngModel)]="searchTerm"
(keyup)="search()"
/>
</div>
</form>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Country</th>
<th scope="col">Area</th>
<th scope="col">Population</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let country of countries | searchFilter: searchTerm; let i = index">
<td scope="row">{{ i + 1 }}</td>
<td>{{ country.name }}</td>
<td>{{ country.area }}</td>
<td>{{ country.population }}</td>
</tr>
</tbody>
</table>
We have to use a CSS class to style the table and search bar input UI. Edit the app.component.scss for style.
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
th {
background-color: red;
border: 1px solid red;
}
td {
border: 1px solid #dddddd;
}
td, th {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
}
.wrap{
.search {
width: 100%;
position: relative;
display: flex;
}
.searchTerm {
width: 100%;
border: 3px solid #00B4CC;
padding: 5px;
height: 20px;
border-radius: 5px;
outline: none;
color: #9DBFAF;
}
.searchTerm:focus {
color: #00B4CC;
}
p{
color: #383c52;
}
}
form {
input {
width: 50% !important;
margin: 2px 0 20px 20px;
}
}
Related posts
- How to calculate base64 image size in Angular
- How to install Angular material
- How to implement CKEditor in Angular
- How to use to implement HighCharts Angular
Thanks! <3
Thanks a lot for the guidance.
God bless you.
export class AppComponent implements OnInit {
searchTerm: string;
countries: Country[];
allCountries: Country[];
How to initialise these variables
Try this
searchTerm: string = ”;
countries: Country[] = [];
allCountries: Country[] = [];