How to attach MatPaginator to datasource coming from server in angular material table? How to attach MatPaginator to datasource coming from server in angular material table? typescript typescript

How to attach MatPaginator to datasource coming from server in angular material table?


You have to wait for your paginator to be instantiated before "linking" it to your MatTableDataSource, so usually, you would listen to AfterViewInit hooks to get the paginator through @ViewChild(MatPaginator) paginator: MatPaginator;

But as your data is asynchronous as well you should

  1. init an empty DataSource
  2. populate the dataSource when your data is ready
  3. link the paginator after the view has been rendered

Could you try this ?

export class YourComponent implements AfterViewInit {  private this.matdatasource;  // get refereence to paginator  @ViewChild(MatPaginator) paginator: MatPaginator;  constructor (private http: HttpClient) {    // 1/ init    this.matdatasource = new MatTableDataSource([]);    this.http.get('http://example.org',{headers: this.headers})      .subscribe(res => {         // 2/ populate with data        this.matdatasource.data = res.data;      });  }     // 3/ link paginator when empty dataSource is created  // and paginator rendered  ngAfterViewInit() {    this.dataSource.paginator = this.paginator;  }  }


First, instantiate the paginator

@ViewChild(MatPaginator) paginator: MatPaginator;

Then populate the dataSource

this.matdatasource = new MatTableDataSource([])

And finally

this.dataSource.paginator = this.paginator;

Check this for proper Understanding


You could try @matheo/datasource to build a clean setup of your database and datasource, and get everything in place without headaches.

I've mount different APIs with all kinds of pagination responses (and also no pagination data like Firebase), and I've handled the total count for all those cases with no issues.

Further details can be found at:
https://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6

I could help you with your use case if you like the library
Happy coding!