How to Create Search Filter in Angular: Simple Guide
To create a search filter in Angular, use a
filter input bound with ngModel and filter your data array in the component based on this input. Use Angular's *ngFor to display only items matching the search text dynamically.Syntax
Use an input element with [(ngModel)] to bind the search text. Then use *ngFor to loop through the filtered list in the template. Filter the list in the component by checking if each item includes the search text.
[(ngModel)]: Two-way data binding for input value.*ngFor: Directive to repeat elements for each item.- Filter logic: Use
Array.filter()in component to return matching items.
html
<input type="text" [(ngModel)]="searchText" placeholder="Search..."> <ul> <li *ngFor="let item of filteredItems"> {{ item }} </li> </ul>
Example
This example shows a simple Angular component that filters a list of names as you type in the search box. The list updates instantly to show only matching names.
typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-search-filter', template: ` <input type="text" [(ngModel)]="searchText" placeholder="Search names..." aria-label="Search names"> <ul> <li *ngFor="let name of filteredNames()">{{ name }}</li> </ul> ` }) export class SearchFilterComponent { searchText = ''; names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']; filteredNames() { const filter = this.searchText.toLowerCase(); return this.names.filter(name => name.toLowerCase().includes(filter)); } }
Output
Input box labeled 'Search names...' and a list below that updates to show names matching the typed text.
Common Pitfalls
Common mistakes include:
- Not importing
FormsModulein your Angular module, songModelwon't work. - Filtering the list directly in the template without a method, which can hurt performance.
- Not handling case sensitivity, causing unexpected filter results.
- Forgetting to add
aria-labelfor accessibility on the input.
typescript
/* Wrong: Filtering directly in template (bad for performance) */ <ul> <li *ngFor="let name of names.filter(n => n.toLowerCase().includes(searchText.toLowerCase()))">{{ name }}</li> </ul> /* Right: Use a component method to filter */ filteredNames() { const filter = this.searchText.toLowerCase(); return this.names.filter(name => name.toLowerCase().includes(filter)); }
Quick Reference
- Bind input with
[(ngModel)]for search text. - Filter your data array in a component method.
- Use
*ngForto display filtered results. - Import
FormsModulein your module forngModel. - Make filtering case-insensitive for better UX.
Key Takeaways
Use [(ngModel)] to bind search input to a component property.
Filter your data array in a component method for better performance.
Display filtered results with *ngFor in the template.
Always import FormsModule to enable ngModel binding.
Make search filtering case-insensitive for user friendliness.