Sorting functionality is functional, but the table content remains unsorted within the Angular Material Table

There seems to be a strange issue with the sorting arrows on the table surface. Even though the sorting functionality should be working, it's not sorting the table as expected...

Here is the HTML :

<div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource" matSort>
      <!-- name -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>{{ model.fields.name.label }}</th>
        <td mat-cell *matCellDef="let element"> {{ element.name }} </td>
      </ng-container>

   <!-- ... -->
  </table>
</div>

In my component.ts:

import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

export class DevizaListComponent implements OnInit {
  dataSource = new MatTableDataSource<DevizaInterface>(devizas);
  devizas: DevizaInterface[] = [
    {
      name: 'dollar',
      code: 'USD' ,
    },
    //...
    //...
  ];
  //...

  @ViewChild(MatSort, { static: true }) sort: MatSort;


  //...

  constructor() { }

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

I imported in my app.module.ts this:

import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';

@NgModule({
  imports: [
    MatTableModule,
    MatSortModule,
  ],
})

Despite no error messages displayed in the console, I'm still facing the issue where the sorting arrows appear but the table doesn't sort correctly. What could be causing this problem?

Answer №1

It is likely that this.sort is not defined yet when you assign it to this.dataSource.sort within the ngOnInit method. As a result, the dataSource does not receive sort events. One possible cause of this issue could be a structural directive (such as *ngIf) that conditionally includes the table in the template.

To address this problem, you can change the static value of the @ViewChild decorator and assign the sort property within the ngAfterViewInit lifecycle hook instead. For more information, refer to the Angular documentation on the component's lifecycle.

export class DevizaListComponent implements AfterViewInit {
  ...

  @ViewChild(MatSort, { static: false}) sort: MatSort;

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

It is also recommended to rearrange the order of your class members and create the dataSource object after initializing devizas.

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

Storing service data within Angular2 components

As I work on creating a login service called AuthService for my Angular 2 application, I'm facing unexpected challenges. My main goal is to have a single user object that remains consistent throughout the entire application after a user logs in. This ...

Steps for developing a collaborative module

New to the world of Ionic/Angular development, my project structure looks like this: - src -- /app ---- app.component.ts ---- app.module.ts ---- main.ts ---- ... -- /pages ---- /event-home ------ /event-home.module.ts ------ /event-home.ts event-home.mod ...

The marker is not updating in real-time with the actual latitude and longitude on the Google Maps angular

I have been attempting to update the marker in my Angular Google Map in real-time, but unfortunately it is not working as expected. It only displays the initial static data and then fails to update. Despite conducting a thorough search on Google, I have be ...

Updating the value in React context does not result in the value being updated

I am in the process of developing a simple routing system where users can either be authenticated or not. I have been using hooks to implement this functionality, but so far, it has not been as successful as I hoped for. authProvider.tsx import React, {Di ...

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

What is preventing my function from retrieving user input from an ngForm?

I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input. The "data" parameter in my submit function is the 'value' attribute of the ngForm. Fo ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

"Troubleshooting Angular Reactive Forms: Issue with Dropdown Displaying Incorrect Selected Value

Currently, I'm in the process of constructing a Reactive form using Angular 9 which involves incorporating a dropdown. The code snippet below illustrates the dropdown component: <form [formGroup]="registerForm" (ngSubmit)="onSubmit()"> ... ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Typescript: Implementing the 'types' property in a function returned from React.forwardRef

I'm exploring the option of adding extra properties to the return type of React's forwardRef function. Specifically, I want to include the types property. Although my current implementation is functional, given my limited experience with TypeScri ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

How can I access the .ts variable value within an *ngIf statement in HTML?

My goal is to showcase images every 2 seconds, but currently I am only able to display all of them at once. Below is the HTML line I am using: <img id="bh" routerLink="/" *ngIf="bh?.id == count" [src]="bh?.src" height="42" width="42"/> Here is t ...

Tips for identifying and handling errors in Playwright

I'm going crazy trying to handle a TimeoutError that I know is coming. Currently, I'm testing the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I want to see if there's a way to prevent the TimeoutError from cau ...

What is the most efficient way to retrieve 10,000 pieces of data in a single client-side request without experiencing any lag

Whenever I retrieve more than 10 thousand rows of raw data from the Database in a single GET request, the response takes a significant amount of time to reach the client side. Is there a method to send this data in smaller chunks to the client side? When ...

Tips and techniques for performing Ahead-Of-Time (AOT) compilation using Angular-CLI in your

Currently working on an Angular4 project and exploring the necessity of using AOT with Angular-CLI. Since Angular-CLI operates Webpack2 in the backend and webpack can generate production builds using ng build, is it required to also use AOT with CLI? Furt ...

Angular2 - Integration and utilization of the datepicker component

Is there a way to retrieve the selected date from an input and wrap it in a <p> tag? I've been attempting to use the jQueryUI datepicker and have tried binding events like change and click, but haven't had any success. Can anyone offer som ...

methods for closing dialog box without altering UI in angular

I have a list of charts on my workspace page and have implemented a Delete confirmation dialog box for when I want to delete a selected chart. However, I have encountered a strange issue where when the delete dialog box is open and I click the cancel butt ...