Coding exercise: implement sorting and filtering in Angular.
Model answer
Keep the filter text and sort key as signals and derive the visible list with computed. Copy before sorting so the original list is not changed.
@Component({
selector: 'app-products',
imports: [FormsModule],
template: `
<input [ngModel]="q()" (ngModelChange)="q.set($event)" placeholder="Filter" />
<select [ngModel]="sort()" (ngModelChange)="sort.set($event)">
<option value="name">Name</option><option value="price">Price</option>
</select>
<ul>@for (p of visible(); track p.id) { <li>{{ p.name }} – {{ p.price }}</li> }</ul>`,
})
export class Products {
products = input.required<{ id: number; name: string; price: number }[]>();
q = signal('');
sort = signal<'name' | 'price'>('name');
visible = computed(() => {
const term = this.q().toLowerCase();
const list = this.products().filter((p) => p.name.toLowerCase().includes(term));
return [...list].sort((a, b) => (this.sort() === 'price' ? a.price - b.price : a.name.localeCompare(b.name)));
});
}The old way is a pipe, but a computed signal is clearer and only recalculates when its inputs change.
Tips
- Do not put heavy sorting in a method called from the template without a signal; it runs on every check.
Practise it yourself in the React and Angular code playground.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.