N.J
N.J

Reputation: 1230

Mat Table paginator doesnot works when loading data from a service

I am trying to show a MatTable which populated from a service.

export class UserComponent implements OnInit, AfterViewInit {

displayedUserColumns: string[] = ['id', 'name'];
users: User[] = [];
userDataSource:MatTableDataSource<User>;
errorMessage: string;

@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private userService: UserService) {

}

ngOnInit(): void {
this.userService.getUsers().subscribe({
  next: (user) => {
    this.users = user;
    this.userDataSource = new MatTableDataSource(this.users);
  },
  error: (err) => (this.errorMessage = err),
});
}

ngAfterViewInit() {
this.userDataSource.paginator = this.paginator;
}

The Table Populate properly but it shows the entire list instead of first 5. The paginator doesn't work.

 <table mat-table [dataSource]="userDataSource">

        <ng-container matColumnDef="id">
          <th mat-header-cell  *matHeaderCellDef> No. </th>
          <td mat-cell *matCellDef="let element"> {{element.id}} </td>
        </ng-container>

        <ng-container matColumnDef="name">
          <th mat-header-cell *matHeaderCellDef> Name </th>
          <td mat-cell *matCellDef="let element"> {{element.name}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedUserColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedUserColumns;"></tr>
      </table>
      <mat-paginator  [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

result looks like this

enter image description here

Upvotes: 0

Views: 43

Answers (1)

German Quinteros
German Quinteros

Reputation: 1930

I think the issue is how you are setting the data in the HTTP request.

Try doing this:

constructor() {
  this.userDataSource = new MatTableDataSource([]);
}

ngOnInit(): void {
  this.userService.getUsers().subscribe({
    next: (user) => {
      this.users = user;
      this.userDataSource.data = this.users;
    },
    error: (err) => (this.errorMessage = err),
  });
}

The rest of the code seems to be ok.

Let me know if that works.

Upvotes: 1

Related Questions