Search code examples
angularangular-materialmat-table

Mat-table changes observable


Let's say I have mat-table in html

 <div>
     <table mat-table [dataSource]="mydataDataSource" #myDataSortReference="matSort" matSort multiTemplateDataRows matSortDisableClear>
     <somerows mat-sort-header> </tr></th>
</table>

and in .ts file

  @ViewChildren('mydataSortReference', { read: MatSort }) myDataSortReference: QueryList<MatSort>;

and

  ngAfterViewInit(): void {
    this.myDataSortReference.changes.pipe(takeUntil(this.destroyed$)).subscribe(() => {
    this.sortMyDataMySpecialFunction();
  });
}

Why the changes are emitted after page refresh, but not on first load of the page? What triggers changes of this component?


Solution

  • You need to give "mydataDataSource" an updated value, say something like:

      sortMyDataMySpecialFunction(): void {
         mydataDataSource = UPDATED_TABLE_DATA;
      });
    

    Assuming that sortMyDataMySpecialFunction() does data retrieval before sorting, otherwise as soon as you get your data (from server/etc.) assign it, preferably in the "ngAfterViewInit" function

    Edit: The sortData function gets called on certain occasions:

    Called after changes are made to the filtered data or when sort changes are emitted from MatSort.

    according to the Angular docs