TS :
ngOnChanges() {
this.dataSource = new MatTableDataSource<Data>(this.someData); //work order data
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
HTML :
<table mat-table [dataSource]="dataSource" matSort>
<!-- column which does not sort is : -->
<ng-container matColumnDef="Name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td data-th="Customer Name" mat-cell *matCellDef="let element"> {{element.party.name}} </td>
</ng-container>
I have tried all the way search in Google along with this site also still no answer, Have tried all the answers related to : mat-sort-header / mat-sort not working on a particular column
but no solution please help.
4
Answers
There are actually 2 issues here.
you are not initializing the matSort correctly.
The code you put in the ngOnChanges should be in the ngAfterViewInit (see [official doc](https://material.angular.io/components/table/overview#sorting with working code)
you have to help material to understand how to sort your column. Material assumes the column name is the same as your object property. So here, Material is trying to sort based on
element.Name
, which does not exists. You have to define sortingDataAccessor, telling something like "if you want to sort Name column, have a look to element.party.name instead".Update sorry, I just check and not work, please remove upvote
usemat-sort-header='party.name'
By defect short-header gets the value of the columnName but you want to sort by party.name
The best bet is add a new property "name" to the elements of your array.
Update 2 About your comment
If you received from the API an array of object like
You can use pipe map in the way
So your elements are in the way
And use a mat-table in the "normal way"
I’ve also faced the same issue.
matColumnDef and the property name should be same.
in HTML:
in TS:
Also, where you are assigning the datasource:
We can not use an object to order because how is defined the function
sortingDataAccessor
in the MatTableDataSource (see the github).But we can create a class that override this function
Now, we can use
And we can use mat-sort-header a name like: "party.name"
See an example in stackblitz