Issue
I am trying to show data in HTML table through an API and I want to add pagination to it and show 3 or 6 row per page but it is not working. All data showed without pagination while I looking to show 3, 4 or 6 when users click on pagination buttons.
users.component.ts:
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Users } from '../users';
import { ApicallService } from '../apicall.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-users-data',
templateUrl: './users-data.component.html',
styleUrls: ['./users-data.component.css']
})
export class UsersDataComponent implements OnInit, AfterViewInit{
@ViewChild('paginator') paginator: MatPaginator;
users : Users[] =[];
dataSource: MatTableDataSource<Users>;
constructor(public http: HttpClient, private apiService: ApicallService){}
displayedColumns: string[] = ['ID', 'Avatar', 'First Name', 'Last Name'];
ngOnInit(){
this.getUserList();
}
ngAfterViewInit() {
this.dataSource = new MatTableDataSource(this.users);
this.dataSource.paginator = this.paginator;
}
getUserList() {
this.apiService
.getUsers()
.subscribe((data:any) => {
this.users = [data.data];
console.log("users data");
console.log(this.users);
});
}
}
here the html table in user.component.html:
<div class="mat-elevation-z8">
<table mat-table [dataSource]="users">
<ng-container matColumnDef="ID">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="Avatar">
<th mat-header-cell *matHeaderCellDef> avatar </th>
<td mat-cell *matCellDef="let element"> <img src="{{element.avatar}} "> </td>
</ng-container>
<ng-container matColumnDef="First Name">
<th mat-header-cell *matHeaderCellDef> First Name </th>
<td mat-cell *matCellDef="let element"> {{element.first_name}} </td>
</ng-container>
<ng-container matColumnDef="Last Name">
<th mat-header-cell *matHeaderCellDef> Last Name </th>
<td mat-cell *matCellDef="let element"> {{element.last_name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator #paginator [pageSizeOptions]="[2, 4, 6]"
showFirstLastButtons></mat-paginator>
</div>
Solution
because you should assign dataSource to the table, and nost just users.
fix: put ngAfterViewInit
body inside of subscribe and bind the ds instead of just array
getUserList() {
this.apiService
.getUsers()
.subscribe((data:any) => {
this.dataSource = new MatTableDataSource(data.data);
this.dataSource.paginator = this.paginator;
});
}
.....
<table mat-table [dataSource]="dataSource">
Answered By - Andrei
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.