Reputation: 156
I was trying to do a pagination in Angular, so that I can send the correct page number to API. Thus I wrote a code like this;
The .ts file contains this;
pNum = 1;
page_number : number[] = [this.pNum, this.pNum+1, this.pNum+2]
//With the help of this array, there will only be 3 pages shown out of hundreds,
//but there will be previous and next page buttons
public pageSelected(selected) {
if(selected == 'Previous') //if prev is clicked, numbers will decrease by 1
this.pNum--;
else if(selected == 'Next') //if next is clicked numbers will increase by 1
this.pNum++;
else
this.pNum = selected; //if a spesific number was selected, it will stay at the left side out of three numbers
}
Then in the html file, I wrote this code;
<ul class="pagination">
<li class="page-item"><a class="page-link" (click)="pageSelected('Previous')>Previous</a></li>
<li class="page-item" *ngFor="let i of page_number>
<a class="page-link" (click)="pageSelected(i)"> {{i}} </a>
</li>
<li class="page-item"><a class="page-link" (click)="pageSelected('Next')>Next</a></li>
</ul>
Now the thing is, I can get the page numbers correctly, but when I click the numbers, the order of numbers wont change. What I want is for example when the page numbers are 1 - 2 - 3 and I have clicked 2, then they should be going like 2 - 3 - 4. Or when clicked 'Next' button, let the page numbers increase by 1.
How can I do this?
Upvotes: 1
Views: 1358
Reputation: 193
regenerate the array page_number, for this you need to include a new logic in your code (just after changing the pNum) to decide if a regeneration of pages on view are correct or need to change to the upper bound or lower.
for example (pseudocode) if the current page_number.last() == 3 and current value of pNum == 3 then regenerate the page_number array, there are many ways you can do pagging and if you choose this method there are many ways you can regenerate the array, for example if you choose the last page possible then you can calculate the new pages from last to first in a loop where (pNum + 1) is your new last number, then calculate any number of pages till the first (in your case, 3).
Upvotes: 1