The Material Table in Angular is having issues with sorting functionality

I tried implementing the basic example from the angular material website, which displays a table with accurate data but the sorting functionality is not working as expected.

For reference, you can view the StackBlitz demo here: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts

Below is how the TS file looks:

export class TableSortingExample implements OnInit, AfterViewInit {
  ELEMENT_DATA: any;
  dataSource: MatTableDataSource<any>;
  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.ELEMENT_DATA = {
      customerHeader: ["ID", "Name", "Address"],
      customerDataRows: [
        ["1", "Mark", "10"],
        ["2", "John", "110"],
        ["3", "John", "110"]
      ]
    };

    this.dataSource = new MatTableDataSource(
      this.ELEMENT_DATA.customerDataRows
    );
  }
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

And here's a snippet of the HTML file:

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
  <ng-container
    *ngFor="let custColumn of ELEMENT_DATA.customerHeader; let colIndex = index"
    matColumnDef="{{ custColumn }}"
  >
    <mat-header-cell *matHeaderCellDef mat-sort-header
      >{{ custColumn }}</mat-header-cell
    >
    <mat-cell *matCellDef="let customerRow">
      {{customerRow[colIndex]}}
    </mat-cell>
  </ng-container>

  <mat-header-row
    *matHeaderRowDef="ELEMENT_DATA.customerHeader; "
  ></mat-header-row>
  <mat-row *matRowDef="let row; columns: ELEMENT_DATA.customerHeader"></mat-row>
</table>

Answer №1

Consider utilizing key/value objects instead of basic arrays when handling data that relies on their position within the array. By converting your customer data arrays into objects, you can easily implement table sorting functionality in your code.

To update the customerDataRows array in table-sorting-example.ts, make the following changes:

customerDataRows: [
   { ID: "1", Name: "Mark", Address: "10" },
   { ID: "2", Name: "John", Address: "110" },
   { ID: "3", Name: "John", Address: "110" }
]

Additionally, update the code in table-sorting-example.html from {{customerRow[colIndex]}} to {{customerRow[custColumn]}}.

For demonstration purposes, I kept all keys in lowercase, although it's a personal preference. Check out this modified version of your project with these updates.

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

Pressing a button that appears multiple times and is also embedded within layers

I am facing an issue where I need to interact with a button that appears multiple times on the website within nested cards. Specifically, I am trying to locate the card containing a pet named Bala, as shown in the attachment below, and click on the Detail ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

Could you tell me the kind of theme used in Material-UI version 5?

I've decided to switch my project over to MUI version 5 and embrace the use of emotion CSS. It's come to my attention that I need to incorporate the theme property, but now TypeScript is prompting me for a type definition for it. The current code ...

Identifying and handling errors in the outer observable of an RXJS sequence to manage

Encountered a puzzling rxjs issue that has me stumped. Here's the scenario: I have two requests to handle: const obs1$ = this.http.get('route-1') const obs2$ = this.http.get('route-2') If obs1$ throws an error, I want to catch it ...

In search of a practical and functional demonstration showcasing Electron v8 combined with TypeScript

Excuse the straightforwardness of my inquiry, as I am reaching the limits of my patience. I am in search of a practical example demonstrating the use of Electron v8 and TypeScript. The example should be simple and functional, without the need for WebPack, ...

In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a compone ...

Incorporating an Angular 2 application into HawtIO as a plugin

Can we integrate an entire Angular2 application as a plugin in HawtIO? By doing this, we aim to leverage HawtIO as the main container for our OSGi applications, each with its own user interface, allowing us to easily detect and display each UI web app with ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

React Typescript: The element is implicitly assigned an 'any' type as the type does not have an index signature

While attempting to locate a key of an object using an item from an array, I encountered an error... An Element implicitly has an 'any' type because type lacks an index signature I've replicated the issue in this sandbox https://codesandbo ...

Why has Jasmine decided not to wait for my promises to finish?

Utilizing the FileSystem API to generate a directory with 2 entries for a test, I am facing an issue where Jasmine does not wait for the promise to resolve before executing the test, resulting in failure. Despite using the async wrapper, the problem persis ...

The inferred type of a TypeScript promise resolved incorrectly by using the output value from a callback function

Although some sections of the code pertain to AmCharts, the primary focus of the question is related to TypeScript itself. The JavaScript functions within the AmCharts library perform the following tasks: export function createDeferred(callback, scope) { ...

Authentication through Auth0 login

After successfully registering a user in Auth0 for login purposes (found in the Users section of the dashboard), I implemented the following code to authenticate the user using an HTML form with username and password fields: public login(username: string, ...

Compilation error in VueJS: missing dependency detected

I am facing an issue in my VueJS project where a file I am referencing seems to be causing a compilation error. Despite being present in the node_modules directory, the dependency is declared as not found. In the image on the left, you can see the directo ...

How to navigate to the bottom of a webpage with Angular 4 using TypeScript's onClick event

Within my component, I have a template that looks like the following. When this div is clicked, the intention is to scroll to the bottom of the page. `<section><div onclick='scrollDown()'>Goto Reports</div></section><d ...

Modify the color of Material UI's Select Component's IconComponent

Currently in my project, I am utilizing MUI's Select Component with the LanguageIcon as the designated IconComponent. My goal is to change the color of this icon from black (default) to white, but I have been unsuccessful in my attempts. I attempte ...

The .angular-cli.json file is causing issues with loading scripts

I have recently updated my .angular-cli.json file by adding new scripts in the following format: "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

Transfer methods utilizing the `this` keyword from a component to a common service

In the development process, I am currently working on breaking down a large component that retrieves data from a selected record and loads it into a FormGroup using FormBuilder. My goal is to divide this component into reusable services and child componen ...

Utilizing handpicked information in Angular: A beginner's guide

Being new to Angular and programming in general, I am currently navigating through the intricacies of Angular and could use some guidance on utilizing selected data. For instance, I would like to use a personnel number view image here and send it to the b ...