Coding exercise: implement pagination in Angular.
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
- Show the edge case: page number after the list gets shorter.
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: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.
- Coding exercise: implement sorting and filtering in Angular.