Lets start by reading data form the service(In service we read data form the json file)
export class AppComponent implements OnInit {
public products: any[] = [];
curPage: number;
pageSize: number;
constructor(private _Products: ProductService) { }
ngOnInit(): void {
this._Products.getJSON().subscribe(response => {
this.products = response.items;
});
this.curPage = 1;
this.pageSize = 10; // any page size you want
}
numberOfPages() {
return Math.ceil(this.products.length / this.pageSize);
};
}
Here we have added two variable, curPage
and pageSize
that can be updated according to the requirement. (click) will navigate user to the desired page. You can update the look and feel for pagination control according to your needs.
and finally in your html :
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of products | slice: (curPage * pageSize) - pageSize :curPage * pageSize">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
<p class="pagination">
<button [disabled]="curPage == 1" (click)="curPage = curPage - 1">PREV</button>
<span>Page {{curPage}} of {{ numberOfPages() }}</span>
<button [disabled]="curPage >= list.length/pageSize" (click)="curPage = curPage + 1">NEXT</button>
</p>
Stackblitz Here
Another way is to use NPM Package : ngx-pagination
Step 1:run the below command over terminal
npm install ngx-pagination --save
Step 2: Read data form Service
export class AppComponent implements OnInit {
public products: any[] = [];
constructor(private _Products: ProductService) { }
ngOnInit(): void {
this._Products.getJSON().subscribe(response => {
this.products = response.items;
});
}
}
Step 3: Import dependency in app.module.ts
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgxPaginationModule --> this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now let's have a look on the code inside app.module.ts where the ngx-pagination module has been imported
Step 4: Update view from app.component.html
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of products | paginate:{itemsPerPage: 5, currentPage:p}">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
<pagination-controls (pageChange)="p=$event"></pagination-controls>
Step 5: Run the app
Run the app over the terminal with npm start
Stackblitz Here