Starting on a Fresh Page

The grid view needs pagination.  No surprise there- when creating something like an audit log, you usually don’t want to just dump all the data onto one screen- that could be thousands of entries.

So we use a service to automatically group the entries into pages.  We started with a method that will create a blank array and initialize it with ‘page 1’.  Then we find the total pages the array will have using the data that’s to be displayed.  Finally, we loop through the length of total pages and push a new number for each page onto the original array.  The number in the array will be the index of the first item on that page (from the master array of all log entries we got from the server).  I know- doing it this way will be slow on first load, and we may look into grabbing the first bunch of entries, then lazy loading the rest, but for now, we just grab them all.

this.paginationArray = [1];
let totalPages = Math.ceil(this.totalEntries / this.maxItemsOnPage);
for(let i = 1; i < totalPages; i += 1) {
    this.paginationArray.push(i * this.maxItemsOnPage + 1);

this.maxItemsOnPage is a number we initially set to 10- it just tracks how many entries we want to show on each page.  It’s stored in a variable because the user can change it- they can show 10, 25, or 50 items per page- each time they change that option, this variable updates and so does our pagination list.

Initially, we used Math.round to get the totalPages variable, but it caused a bug where sometimes the last page was omitted from the listing.  Math.round does a traditional round on a number- so if we came up with totalPages as 4.7, it was fine- rounds to 5.  But if it was 4.3, we lost the last page when it rounded down to 4.  Using Math.ceil ensures that anything over 4 rounds up to 5, and we have the correct number of pages.

In our HTML template, we just set up an *ngFor angular loop and we’re good to go.  To be honest- there’s more logic in the template than I like- things got a little complicated with tracking which page was the current page and adding/removing classes conditionally, but we will cover that later.

Short entry this week, but stay tuned for the exciting conclusion next week- where we limit the number of pages that show in the navigation to 5- then automatically update that as a user scrolls through the pages, revealing more as they go.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s