Pagination has helped combat performance issues for a long time. However, with the massive use of mobile screens, page up and down has become annoying and impractical.
This article will try to move on from this:
To this:
Requirements:
- Minimal knowledge of angularJs and Angular is expected, including javascript and typescript.
Sponsors:
- This article has been created thanks to Anura's support.
From pagination to infinite scroll and beyond
- To avoid showing all existing accounts in the system, we used the ui-bootstrap pagination directive. However, the UX of this view was significantly worse on mobile. For this reason, it was decided to use the Angular Material's CDK and implement a view with infinite scroll.
- Although the problem had been fixed on mobile phones, too much space was being wasted on the web version. However, implementing a grid was more difficult than expected.
After investigating the library, we discovered that Angular Material expects a single column in its virtual scroll. In this way, solving the problem with only CSS was not going to work.
-
Testing various alternatives, the following solution was reached:
- The set of "N" elements is obtained
- The set of elements is divided into groups of 4 elements, forming an Nx4 matrix
- A double "ngFor" is applied: the first to loop through the array, and the second to loop through each group of four elements
In this way, it was possible to have a single column with four elements per row, show them as a grid.
-
Although the victory seemed consecrated, problems appeared:
- Four items per row is a very small number if you have a very large screen
- Certain screen sizes will fit three items in a row and one below.
- Therefore, it was necessary to choose a number of elements per row according to the size on the screen, adjusting said quantity in case the screen size changed again.
- For this, the following architecture was created:
- A structural directive to get the infinite scroll elements
- A component to calculate the optimal number of elements per row
- The corresponding HTML that will contain the cdk-virtual-scroll-viewport"
- An attribute directive to apply the grid styles
- A module to declare the created entities
Perfect! After several hours, an infinite scroll with multiple columns has been obtained. In your face, Google!
Conclusion:
- Although creating a virtual scroll with several columns was challenging and fun, it is worth clarifying that if a library has certain limits, as a professional developer you have to ask yourself if the chosen path is really the correct one. On the other hand, there are already created libraries that solve this problem (ngx-virtual-scroller). Thus, reinventing the wheel should be avoided whenever possible.
Top comments (0)