I have 2 components. Both have mat-table and paginators and pagination is working for one component and not working for the other component though the code is similar. Below
Angular 7+ (8/9) There is another elegant solution to solve that problem.
Short Version
Immediately after setting data source invoke ChangeDetectorRef.detectChanges().
Long Version
Step1:
Import ChangeDetectorRef & Material related stuff
import { ..., ChangeDetectorRef } from '@angular/core';
import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';
Step2:
Set class-properties in your component
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
Step3:
Inject ChangeDetectorRef in your constructor
constructor (..., private cdr: ChangeDetectorRef, ...) { ... }
Step4:
Set data source and invoke detectChanges()
this.dataSource = new MatTableDataSource (MY_DATA);
this.cdr.detectChanges();
Optional Steps:
After that, you can set other properties like
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;