Coding exercise: implement sorting and filtering in Angular.

Angular practical coding · Freshers and experienced

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

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