Sorting the material table based on the column IDs, which usually correspond to the column names, may not align with the properties of the data

.ts

this.displayedColumns = [
      { key: 'id', header: '#' },
      { key: 'fullname', header: 'Full name' },
      { key: 'email', header: 'email' },
      { key: 'roleName', header: 'Role' }
];
this.displayedColumnsKeys = this.displayedColumns.map(col => col.key);

.html

<table mat-table [dataSource]="dataSource" multiTemplateDataRows matSort class="mat-elevation-z8">

  <ng-container *ngFor="let dispCol of displayedColumns; let colIndex = index" matColumnDef="{{dispCol.key}}">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> {{dispCol.header}} </th>
    <td mat-cell *matCellDef="let element"> {{element[dispCol.key]}} </td>
  </ng-container>

  <!-- Expanded Content Column - The detail row is made up of this one column that spans across all columns -->
  <ng-container matColumnDef="expandedDetail">
    <td mat-cell *matCellDef="let element" [attr.colspan]="displayedColumns.length">
      <div class="example-element-detail"
           [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
        <div class="example-element-diagram">
          <div class="example-element-position"> {{element.position}} </div>
          <div class="example-element-symbol"> {{element.symbol}} </div>
          <div class="example-element-name"> {{element.name}} </div>
          <div class="example-element-weight"> {{element.weight}} </div>
        </div>
        <div class="example-element-description">
          {{element.description}}
          <span class="example-element-description-attribution"> -- Wikipedia </span>
        </div>
      </div>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumnsKeys"></tr>
  <tr mat-row *matRowDef="let element; columns: displayedColumnsKeys;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </tr>
  <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
  <tr class="mat-row" *matNoDataRow>
    <td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
  </tr>
</table>

It seems like the sorting functionality is not working properly due to mismatching header ids and properties in the array of objects fetched from the backend.

I've realized that I need to create a custom sortingDataAccessor function, but I'm unsure about how to go about implementing it. Any guidance on this matter would be greatly appreciated!

Answer №1

Give this a shot:

@ViewChild(MatSort) sort: MatSort;

ngOnInit() {
  this.dataSource = new MatTableDataSource(yourData);
  this.dataSource.sortingDataAccessor = (row, key) => {
    switch(key) {
      case 'columnName': return row.serverName;
      default: return row[key];
    }
  };
  this.dataSource.sort = sort;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve distinct objects based on LocId across all locations?

Encountering an issue while working on Angular 7: unable to return distinct or unique objects based on LocId. The goal is to retrieve unique objects from an array of objects containing all Locations. allLocations:any[]=[]; ngOnInit() { this.locationsServ ...

Setting up the foundations in Angular 4

Using WebStorm 2017.1.4, I am working on creating the front end of my J2EE application. Within this project, I have two components: "about" and "contacts". In the latter component, my goal is to include all contacts from a MySQL database. However, I encoun ...

Learn how to configure an Angular2 Template Driven form element by implementing two-way binding and integrating template driven form validation techniques

Can anyone help me figure out the correct way to set up an Angular template driven form element for both validation and two-way binding? I've tried using ngModel in different ways, but cannot seem to achieve two-way binding without encountering issues ...

Testing Angular components using mock HTML Document functionality is an important step in

Looking for help on testing a method in my component.ts. Here's the method: print(i) { (document.getElementById("iframe0) as any).contentWindow.print(); } I'm unsure how to mock an HTML document with an iframe in order to test this meth ...

Struggling with Angular Material not functioning properly? All features seem to be included

I am having trouble with my website being split into different parts. I have included the CSS inside the head tag and the JS in the body, but it is still not working properly. - setup and I have also tried the following: <html ng-app="StarterApp"> ...

Resolving CORS Error in Angular and PHP: A Comprehensive Guide

My current project involves learning Angular and creating a solution that communicates with an IIS Server running on PHP as an API. The IIS server is set up with Windows Authentication to authenticate users, and the combination of IIS/PHP is functioning p ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

Ensure that the variable is not 'undefined' and that it is a single, clean value

In my node backend project, I've encountered a situation with my TypeScript code where a variable occasionally prints as the string 'undefined' instead of just being undefined. Is there a more elegant way to check that the variable is not eq ...

Errors TS2585 and TS2304 encountered during compilation of TypeScript file using Axios

What steps should I take to fix the errors that arise when attempting to compile my TypeScript code using tsc index.ts? node_modules/axios/index.d.ts:75:3 - error TS1165: In an ambient context, a computed property name must reference an expression of lite ...

Error in NextJS Middleware Server: Invalid attempt to export a nullable value for "TextDecoderStream"

I've recently created a straightforward Next.js application using bun (version 1.0.4, bun create next-app), incorporating app routing with Next.js version 13.5.4 and a designated source directory. My goal was to implement a middleware that restricts a ...

Limiting the height of a grid item in MaterialUI to be no taller than another grid item

How can I create a grid with 4 items where the fourth item is taller than the others, determining the overall height of the grid? Is it possible to limit the height of the fourth item (h4) to match the height of the first item (h1) so that h4 = Grid height ...

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

Error code 2532 occurs when trying to access an object using square brackets in TypeScript

Encountered the ts error: Object is possibly 'undefined'.(2532) issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum. Below is a concise example to showcase this problem: en ...

RxJS: the art of triggering and handling errors

This is more of a syntax question rather than a bug I'm facing. The process is straightforward: Send an HTTP request that returns a boolean value If the boolean is true, proceed If the boolean is false, log a warning and stop the flow. To handle ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

Enhance the express request to include the user parameter for the passport

I am currently utilizing Passport for authentication in an Express application. This authenticates the user and sets it on the Express response. As I am using TypeScript, trying to set the request type to Request in the route definitions results in an erro ...

Angular encountered an error when trying to access the property "fruits" of an undefined object

When working with Angular, I encountered an issue where I received the error message "cannot read property 'fruits' of undefined." Within my class definition, I have included the following: export class MyClass implements OnInit { fruits: any[] ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

How to programmatically close an Angular 5 Modal

In my current project, I am working with Angular 5. One of the functionalities I have implemented is a modal window. The HTML structure for this modal looks like this: <div class="add-popup modal fade" #noteModal id="noteModal" tabindex="-1" role="dia ...

Error message possibly undefined when attempting to apply fill gradient to Highcharts area-spline chart

Currently working with angular 12 and utilizing highcharts. I've been attempting to fill the area spline color with a gradient, but have encountered an error in the process. Any suggestions on how to resolve this issue or what step may be causing the ...