Adding mat-paginator to Html list or mat-list

Collins Kipkemoi
2 min readMay 9, 2021

--

When you have a large data set or documents you might want to display this data in an organized, clean, and manageable way, then you need pagination or paging.

This tutorial shows how mat-paginator can be used with Html list.

Prerequisites — Angular, Angular material.

We assume you have an angular app already set up. Next is to add angular material

Install angular material to your angular app, by ng add @angular/material

After installing Angular Material, now we can continue, here is our list before the paginator

list before paginator

Next, import MatPaginatorModule in the angular app module and add it to the imports array.

import {MatPaginatorModule} from '@angular/material/paginator';imports: [
MatPaginatorModule
],

Next, add a paginator just below the Html list

........
</ul>
<mat-paginator #paginator [length]="dataSize" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>

Next, add the viewChild decorator to component.ts for the paginator

@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

Next, we are going to import merge and of from rxjs and startWith, switchMap from rxjs/operators

import { merge, of } from 'rxjs';import { startWith, switchMap } from 'rxjs/operators';

Now we are going to add little logic to our component.ts to wire up the paginator.

// this method will link data to paginator
linkListToPaginator() {
// merge simply joins all this operators and creates an //observable that listen to paginator page events
merge(this.paginator.page).pipe( startWith({}), switchMap(() => {
// creates an obserbable of sample data
return of(data);
}))
.subscribe(res => {
const from = this.paginator.pageIndex * 10; const to = from + 10; this.dataSource = res.slice(from, to);});}

And that's it, let's have a look at our page.

paginator added

Note that the data used here is mock data, if it was data from the server same principle will apply.

Now, let's add mat-list and make our list look better.

Import MatListModule and add to your import array in app.moudule.ts

import {MatListModule} from '@angular/material/list';imports: [
MatPaginatorModule,
MatListModule
],

Next replace <ul> with <mat-list> and <li> with <mat-list-item>

<mat-list role="list"><mat-list-item class="mat-list" role="listitem" *ngFor='let i of dataSource'>{{i.value}}</mat-list-item></mat-list>

Here is the preview.

Final code

--

--