I am having some issues, In my app i have some paginated results but when I add the variable let i = index in ngFor, i can get the results for the first 10 items only not the paginated items? So If i go to page 2 and click on teh first item the index is 1 again as I have done index + 1.
So far code is:
import { Component, VERSION, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular ' + VERSION.major;
collection: any;
p: number;
itemsPerPage = 10;
totalItems: any;
constructor(private http: HttpClient) {}
ngOnInit() {
this.getAllData();
}
getIndex(i) {
console.log(i + 1);
}
getAllData() {
const url = `https://xxxx/api/houses?page=1&pageSize=${this.itemsPerPage}`;
this.http.get(url).subscribe((data: any) => {
console.log(data);
this.collection = data;
this.totalItems = 450;
});
}
getPage(page) {
const url = `https://xxxx/api/houses?page=${page}&pageSize=${this.itemsPerPage}`;
this.http.get(url).subscribe((data: any) => {
console.log(data);
this.collection = data;
this.totalItems = 450;
});
}
}
component.html
<ul>
<li *ngFor="let item of collection | paginate: { itemsPerPage: itemsPerPage , currentPage: p, totalItems: totalItems } let i = index"> {{item.name}} <button (click)='getIndex(i)'>Index</button>
</li>
</ul>
<pagination-controls (pageChange)="getPage(p = $event)"></pagination-controls>
Any ideas?
You can update the getIndex
method like this to calculate the total index with taking the pagination into account:
getIndex(i) {
let pageCoefficient;
if (!this.p || this.p === 1) {
pageCoefficient = 0;
} else {
pageCoefficient = (this.p - 1) * this.itemsPerPage;
}
console.log(i + 1 + pageCoefficient);
return i + 1 + pageCoefficient;
}