How to implement infinite scroll in Angular

Piyush Jain
2 min readMay 1, 2020

--

image source — https://christianliebel.com/wp-content/uploads/2016/02/Angular2-825x510.png

In this article we will be implementing infinite scroll in angular material table.

What is Infinite Scroll

Infinite scroll is you don’t load data in one go on frontend instead you load only limited row on page load and once user starts scrolling you load next chunk of data.

Without wasting any time lets start.

first of all create a new project and install material and cdk using these commands.

ng new angular-material-table-infinite-load

cd angular-material-table-infinite-load

npm install @angular/material @angular/cdk

after this add these two modules in your root module.

https://gist.github.com/piyush303/2592c6e66600c3f285ba9c12c2910ce4.js

check on line no 2 and 4, we have added 2 module, one to use angular material and another one to use material table.

Now create a new component using ng generate component app/table`. This will generate a new component inside app folder.

After that copy this code in you table.component.ts file.

https://gist.github.com/piyush303/2639a07c2cdd116a95e6f3995fa6d5dc.js

Now add this code in your table.component.html

https://gist.github.com/piyush303/f5b4757e4b0c25f552dea4fdf6002c3a.js

This is default angular material table code with one addition. We added a scroll event in mat-table. So whenever user will scroll on table onTableScroll($event) will be called.

Now add this code in your table.component.scss

.example-container {  
display: flex;
flex-direction: column;
max-height: 500px;
min-width: 300px;
}
.mat-table {
overflow: auto;
max-height: 500px;
}

if you will notice in table.component.ts we have declared these 3 variable.

start: number = 0;  
limit: number = 15;
end: number = this.limit + this.start;

start is from which index we have to pick data from array. In starting will be 0.

Limit is how many new items we have to load once user start scroll.

end is till which index we have to pick data from array. In will always be start+limit.

Boom, now you have successfully implemented infinite scroll in angular app using material table.

you can get working code here.

https://stackblitz.com/edit/angular-material-table-infinite-load

Thanks for reading this article.

Don’t forget to clap.

Reference — https://material.angular.io/

Read Next

`

--

--

Piyush Jain

An avid front-end technologist with 9+ years of web industry experience. Self-motivated professional with broad technical skill-set and very strong attention.