Skip to content

docs-bug(COMPONENT): Implementation of asynchronous data sorting should be documented #27708

Closed
@nicos68

Description

@nicos68

Documentation Feedback

When retrieving data asynchronously (e.g. from a REST service, see example below), if I reinstanciate the MatTableDataSource object I use in the MatTable component, everything I do works fine except sorting.
example:

//...
export class TableSortingExample implements AfterViewInit {

  dataSource = new MatTableDataSource();

  constructor(/*...*/) {
    this.http.get("myservice").pipe(
        tap((response) => {
          this.dataSource = new MatTableDataSource(response); // <- reinstanciating the Datasource. 
                                                              // Breaks sorting.
        })
      ).subscribe();
    }

  @ViewChild(MatSort) sort: MatSort;

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

If I do something like this, clicking on the sort arrows has no effect.

Whereas if I use something like that:

//...
export class TableSortingExample implements AfterViewInit {

  dataSource = new MatTableDataSource();

  constructor(/*...*/) {
    this.http.get("myservice").pipe(
        tap((requests) => {
          this.requests.data = requests; // <- Mutate reference to `data` property of the Datasource.
                                         // Works fine.
        })
      ).subscribe();
    }

  @ViewChild(MatSort) sort: MatSort;

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

Then everything works. This took me several hours to figure out, and I would probably never have found out, wouldn’t it have been for this. I think this should be documented.

Context:
Angular & Angular Material versions : 16.1.7

Affected documentation page

https://material.angular.io/components/table/overview#sorting

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: material/tabledocsThis issue is related to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions