Given a list of users, build a user data table that displays users in a paginated format.
1import { Component } from '@angular/core';23import users from '../data/users';45type User = (typeof users)[number];6type SortField = keyof User;78@Component({9 selector: 'app-data-table',10 templateUrl: './data-table.component.html',11})12export class DataTableComponent {13 readonly columns: ReadonlyArray<{ label: string; key: SortField }> = [14 { label: 'ID', key: 'id' },15 { label: 'Name', key: 'name' },16 { label: 'Age', key: 'age' },17 { label: 'Occupation', key: 'occupation' },18 ];19 readonly pageSizes = [5, 10, 20];2021 page = 1;22 pageSize = 5;2324 get totalPages(): number {25 return Math.ceil(users.length / this.pageSize);26 }2728 get pageUsers(): Array<User> {29 const start = (this.page - 1) * this.pageSize;30 return users.slice(start, start + this.pageSize);31 }3233 changePageSize(event: Event): void {34 this.pageSize = Number((event.target as HTMLSelectElement).value);35 this.page = 1;36 }37}
Page state lives in class fields, with derived getters exposing the total pages and visible users. Template event handlers update the fields and reset pagination when the page size changes.
Data tables are frequently asked about during front-end interviews, as displaying paginated data with filtering functionality is a UI pattern built at almost every company.
Since the table skeleton has been provided, we can focus on the state and data manipulation aspects of the data table.
State is straightforward. Only two state values are needed: the current page and the page size. Since the data does not change in this case, there's no need for the user data to be part of state.
These state values are manipulated by the page size <select> and prev/next buttons.
The maximum number of pages can be derived from the number of users divided by the page size, so it does not need to be part of state.
We implement a function paginateUsers that takes in the list of users, the page number, and the page size. It will return the list of users for the current page and the total number of pages.
To determine the list of users for the current page, we can determine the start and end indices, then use Array.prototype.slice() to extract the appropriate slice from the users list:
Array.prototype.slice(), it doesn't matter if the end index exceeds the size of the list.paginateUsers() will be called in the render path, and the returned pageUsers array contains the current page of users to be rendered. The rendering code doesn't need to be changed much.
Some other user experience improvements we can make:
console.log() statements will appear here.