0
votes

I get a list of 100+ users fetched from an api. Now I would like to implement that data in the angular material table.

Is it possible in the frontend that i display only 10 users in pageSize and have pagination. I tried but it displays all available users eventhough I have pagination module implemented.

<mat-paginator [pageSize]="10" showFirstLastButtons></mat-paginator>

In the typescript code, i get the list from the parent component.

import {Component, OnInit, ViewChild, Input, OnChanges} from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit, OnChanges {
  @Input() users;

  displayedColumns = ['name', 'id'];
  dataSource;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor() { }

  ngOnChanges() {
    this.dataSource = new MatTableDataSource<any>(this.users);
  }

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
  }
}
2
can you show your .ts file?mintquan
@mintquan I have updated the code.. I get the list from the parent component. So i use it on the ngOnChanges to get the list of data.surazzarus
try in after view Init hook ngAfterViewInit() { this.dataSource.paginator = this.paginator; }Vikas
@Vikas it doesn't work eithersurazzarus

2 Answers

1
votes

Really you needn't use ngOnChanges, but if you use, you need asign datasource.paginator in ngOnChanges too.

Also, take account if the paginator is visible or not when you asign to your datasource.

If you use in ngOnInit you need use static:true

@ViewChild(MatPaginator,{static:true}) paginator: MatPaginator;

but remember that, in that case the paginator can not be under a *ngIf, else use ngAfterViewInit

BTW, if you has access to the API or the paginator is on server -not in frontend, you can take a look to this SO

0
votes

Anyways I made it work. Putting the paginator in ngOnChanges

ngOnChanges() {
    this.dataSource = new MatTableDataSource<any>(this.users);
    this.dataSource.paginator = this.paginator;
}