0

I have this json attached to a mat-table

const pendingUsers: pendingUsersData [] = [{
  'autoReLogin': false,
  'rolesAccess': [{
    'requestReason': 'because i need it',
    'status': 'pending',
    'role': 'API_ApplicationDeveloper'
  }],
  'userId': 'f123132',
  'emailId': 'me@google.com',
  'firstName': 'Me',
  'lastName': 'ME',
  'country': 'IN'
}, {
  'autoReLogin': false,
  'rolesAccess': [{
    'requestReason': ' ',
    'status': 'pending',
    'role': 'API_ApplicationDeveloper'
  }],
  'userId': 'F12455',
  'emailId': 'ak@gmail.com',
  'firstName': 'AKl',
  'lastName': 'M',
  'country': 'IN'
}, {
  'autoReLogin': false,
  'rolesAccess': [{
    'requestReason': ' ',
    'status': 'pending',
    'role': 'API_ApplicationDeveloper'
  }],
  'userId': 'F14123',
  'emailId': 'pg@gmail.com',
  'firstName': 'Prs',
  'lastName': 'Gpta',
  'country': 'IN'
}, {
  'autoReLogin': false,
  'rolesAccess': [{
    'requestReason': 'exception_response_reason',
    'status': 'pending',
    'role': 'API_ApplicationDeveloper'
  }],
  'userId': 'F99349',
  'emailId': 'ank.sh@gmail.com',
  'firstName': 'Ank',
  'lastName': 'Shy',
  'country': 'IN'
}];

I am using the following code to sort columns

ngAfterViewInit() {
this.pendingUsersDataSource.paginator = this.paginator.toArray()[0];
this.pendingUsersDataSource.sort = this.sort.toArray()[0];
this.pendingUsersDataSource.sortingDataAccessor = (item, property) => {
  switch (property) {
    case 'rolesAccess[0].requestReason': return item.rolesAccess[0].requestReason;
    default: return item[property];
  }
};

}

The sort seems to work fine for all columns except the ones which are attached to rolesAccess. I would also be able to sort on the basis of requestReason and role. At this point sorting does not seem to happen.

Sujith
  • 105
  • 1
  • 7

1 Answers1

0

Try this for nested objects:

this.dataSource.sortingDataAccessor = (item, property) => {
  if (property.includes('.')) return property.split('.').reduce((o,i)=>o[i], item);
  return item[property];
};
Erik Schaareman
  • 191
  • 1
  • 2