Coding exercise: implement pagination in Angular.

Angular practical coding · Freshers

Model answer

Keep the page number in a signal and compute the visible slice and page count. For big data, send page and limit to the server and show only what it returns.

@Component({
  selector: 'app-paged',
  template: `
    <ul>@for (x of slice(); track x.id) { <li>{{ x.name }}</li> }</ul>
    <button (click)="page.set(page() - 1)" [disabled]="page() === 1">Previous</button>
    <span> Page {{ page() }} of {{ pages() }} </span>
    <button (click)="page.set(page() + 1)" [disabled]="page() === pages()">Next</button>`,
})
export class Paged {
  items = input.required<{ id: number; name: string }[]>();
  size = 5;
  page = signal(1);
  pages = computed(() => Math.max(1, Math.ceil(this.items().length / this.size)));
  slice = computed(() => {
    const p = Math.min(this.page(), this.pages());
    return this.items().slice((p - 1) * this.size, p * this.size);
  });
}

computed values recalculate only when the signals they read change. For server paging, put the page in the request params and use switchMap or an httpResource.

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