Filtering a List in Angular (With Code Examples)
In Angular, filtering a list based on user input is straightforward.
Here's how you can do it using a custom pipe.
Step 1: Set Up Your Data
Let's assume you have a list of items:
items = [
{ id: 1, text: 'First item' },
{ id: 2, text: 'Second item' },
{ id: 3, text: 'Third item' }
];
Step 2: Create the Filter Input
Add an input box to filter the list in your component's HTML file.
<input [(ngModel)]="query" placeholder="Search items...">
This input is bound to the query
variable. The value of query
will change as the user types.
Step 3: Display the Filtered List
Use the @for control flow syntax to loop through the items and apply the filter:
<div *ngFor="let item of items | search:'id,text':query">
{{ item.text }}
</div>
This code uses the search
pipe, which we'll create next.
Step 4: Create the Search Pipe
Pipes are a powerful way to transform data in Angular.
Here’s how to create a custom search
pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(value: any[], keys: string, term: string): any[] {
if (!term) return value;
return value.filter(item =>
keys.split(',').some(key =>
item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])
)
);
}
}
Step 5: Use the Pipe in Your Component
First, ake sure to declare the SearchPipe
in your @NgModule
:
@NgModule({
declarations: [
SearchPipe,
// other components
]
})
export class AppModule {}
Now, as the user types in the input box, the list will filter in real-time, showing only the items that match the search term.
And there you have it!
This method is simple, powerful, and flexible, perfect for filtering lists in your Angular applications.
Daniel Kreider