We have a DataListComponent that shows a data we pull from a service. DataListComponent also has a PagerComponent as it's child.
PagerComponent creates page number list based on total number of pages it gets from the DataListComponent. PagerComponent also lets the DataListComponent know when user clicks any page number via Output property.
import { Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataListService } from './dataList.service';
import { PagerComponent } from './pager.component';
@Component({
selector: 'datalist',
template: `
<table>
<tr *ngFor="let person of personsData">
<td>{{person.name}}</td>
<td>{{person.surname}}</td>
</tr>
</table>
<pager [pageCount]="pageCount" (pageNumberClicked)="pageChanged($event)"></pager>
`
})
export class DataListComponent {
private personsData = null;
private pageCount: number;
constructor(private dataListService: DataListService) {
var response = this.dataListService.getData(1); //Request first page from the service
this.personsData = response.persons;
this.pageCount = response.totalCount / 10;//We will show 10 records per page.
}
pageChanged(pageNumber: number){
var response = this.dataListService.getData(pageNumber); //Request data from the service with new page number
this.personsData = response.persons;
}
}
@NgModule({
imports: [CommonModule],
exports: [],
declarations: [DataListComponent, PagerComponent],
providers: [DataListService],
})
export class DataListModule { }
PagerComponent lists all the page numbers. We set click event on each of them so we can let the parent know about the clicked page number.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'pager',
template: `
<div id="pager-wrapper">
<span *ngFor="#page of pageCount" (click)="pageClicked(page)">{{page}}</span>
</div>
`
})
export class PagerComponent {
@Input() pageCount: number;
@Output() pageNumberClicked = new EventEmitter();
constructor() { }
pageClicked(pageNum){
this.pageNumberClicked.emit(pageNum); //Send clicked page number as output
}
}