1

I'm working on formArray in mat-table and the table can be sort. I just want a simple sorting based on id. Everything working good except sort. Please let me know where I made mistake here. Here is my code: Stackblitz

1 Answer 1

1

It's obvious that you got confused with the Angular Material table examples.

If you take a look on MatTable example with SortHeader you will notice that you can add your Sort child to your dataSource only if your dataSource is an instance of MatTableDataSource.

like: dataSource = new MatTableDataSource(ELEMENT_DATA);

@ViewChild(MatSort) sort: MatSort;

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

This doesn't work in your case, since your albums which's your dataSource is a formArray, so you can solve it by using the matSortChange event that calls your custom method of sorting.

HTML:

<mat-table
    matSort
    [dataSource]="albums.controls"
    (matSortChange)="sortAlbums($event)">
        <!-- your columns here -->
</mat-table>

Typescript:

sortAlbums(sort: Sort) {
    var list: Album[] = this.albums.value;
    switch (sort.direction) {
      case 'desc':
        list = list.sort((a, b) => b.id - a.id);
        break;
      default:
        list = list.sort((a, b) => a.id - b.id);
        break;
    }
    this.albums.patchValue(list);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.