Trouble sorting Angular Material Data Table?

[UNIQUE LINK] I'm working on a simple Angular material data table with sorting.

I've gone ahead and added the MatSortModule, used @ViewChild in my component class, included the directives, set up the dataSource.sort property, and even see the arrow when hovering over the table, but unfortunately, the data isn't sorting as expected.

Any suggestions or ideas?

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatTableDataSource, MatSort } from "@angular/material";

    class Task {
      id: string;
      description: string;
      complete: boolean;
    }
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      @ViewChild(MatSort, {static: false}) sort: MatSort;

      /**
      * Control column ordering and which columns are displayed.
      */
      displayedColumns:string[] =  ['id'];
      dataSource: MatTableDataSource<Task>;

      ngOnInit() {
        const tasks: Task[] = [
          { id: '123', description: 'Complete me!', complete: false },
          { id: '321', description: 'You Completed me!', complete: true }];
        this.dataSource = new MatTableDataSource(tasks);
        this.dataSource.sort = this.sort;
      }
    }


    <mat-table class="mat-elevation-z8" [dataSource]="dataSource" matSort>
      <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let row;">{{row.id}}</mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns">
      </mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
    </mat-table>

Answer №1

The ViewChild property associated with MatSort is considered to be undefined during the initialization phase of the component in the ngOnInit method because the view has not been fully set up yet. To fix this issue, you can assign the MatSort instance for your dataSource after the view has been properly initialized by utilizing the ngAfterViewInit lifecycle hook.

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

Answer №2

Having encountered a similar issue, I found that setting the MatSort resolved it. Here's my solution:

@ViewChild(MatSort, {static: false}) set  updateSort (ms: MatSort){
this._sort = ms;
this.refreshDataSource(); }

............................................

ngOnInit(){
this.dataSource = new MatTableDataSource(todos);
this.refreshDataSource();
}


refreshDataSource() {
this.dataSource.sort = this._sort;
}

I hope this explanation proves helpful! :)

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

Deciphering the intricacies of AWS-Config Rules and Alterations in Configuration

Currently, I am utilizing the aws-cdk to create config rules for approximately 15 rules that we need to monitor and receive notifications on. Below is a snippet of the code for reference: // Code snippet showing the creation of multiple config rules My m ...

Obtaining a File type object from a URL (specifically an image) in Vue.js

Suppose I have an image URL like http://localhost/sample.jpg. What is the best way to save this image URL into a File object using native JavaScript API in my component? export default { created () { const imageUrl = 'http://localhost/sample.jpg ...

Is there a way to target the mat-icon element using the icon's name in CSS

I have a group of mat-icons that are automatically generated, meaning I cannot assign them ids or classes. The only way to distinguish between them is by their names: <mat-icon role="img">details</mat-icon> <mat-icon role="img ...

Divergent behavior observed with Bootstrap modal focus trap on official documentation website

Having an issue with Bootstrap modal not trapping focus inside the modal. Surprisingly, it works as expected on the official Bootstrap webpage here. I've used the exact code from the Bootstrap website but for some reason, it's not working in my ...

Looking to showcase the array list on the user interface

I'm attempting to use the map function in JavaScript to display a list, but I keep encountering an error that says "TypeError: Cannot read property 'map' of undefined". import React, { Component } from 'react' import constants fro ...

What is the best way to retrieve data from a form after making an AJAX request to it?

I have a coding challenge where I'm working on creating a button that triggers a modal. The content of the modal is being fetched via AJAX from another PHP file. Inside the modal, there is an input field and I need to pass the value entered in this fi ...

Struggling with implementing Vue.js for making a task list using Bootstrap 5

I'm trying to get the hang of Vue.js. I've been working on setting up a to-do list where users can input tasks, but I'm having trouble getting the list to display correctly when I define the method. It seems like my add() function isn't ...

Showing a global variable from an external JavaScript library

I have integrated some external libraries into my ionic project. One of these libraries includes the declaration of var loading = false; In my page's .ts file, I am "importing" this variable using: declare var loading; Although I can use this vari ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

I am looking to attach a Bootstrap 4 class to the form input field

I needed to apply the "is-invalid" bootstrap4 class when my Angular form field was invalid and touched. I attempted to achieve this with: <input type="text" #name class="form-control" [class.is-invalid]="name.invalid && name.touched" name="Name ...

Determine the finishing time by calculating the sum of the start time and duration

Is there a way to determine the end time by using the start time and duration? I am able to receive these values from an API: data : { 'startTime': 1100, // (the format is in 24hrs i.e 11:00 AM) 'duration' : 60 // (in minutes) ...

Resetting radio buttons and select fields upon dynamically adding a new input field in ReactJS

I'm currently working on creating a stack of input fields, and I want to be able to dynamically add a new input field to the page. My approach involves storing default fields in an array state and using setArr() along with the spread operator to add a ...

How to retrieve values from multiple mat-sliders that are dynamically generated using ngFor loop

Creating multiple mat-sliders dynamically in Angular looks like this: <ng-container *ngFor="let parameter of parameterValues; let i = index;"> <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" i ...

Angular 10: Module Alias Import Not Resolving in VSCode due to Path Mapping Recognition Issue

After updating a project from Angular 8.2 to version 10, I followed the instructions on https://update.angular.io/ and everything seemed fine. However, once I implemented Path Mapping, I started encountering this error everywhere: Cannot find module ' ...

What could be causing my React component to mount after every action?

In my React application, I have a component named Home that triggers an action to fetch groups when it mounts. The action is called in the following way: componentDidMount() { const { fetchRecentGroups } = this.props; fetchRecentGroups(); } The ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...

Using ajax to retrieve quotes and authors from online sources

I've recently started learning javascript and I'm currently working on the Random Quote Machine project on freecodecamp. The main goal is to show a random quote along with its author when the user clicks the "New Quote" button. However, I'm ...

Exploring the JavaScript Bitwise NOT Operator and the toString() Method

Greetings to all in advance! alert((~1).toString(2)); As a result, the output is: -10 However, in PHP/Java, it produces 11111111111111111111111111111110 I'm puzzled. What could be causing Javascript to include a "-" at the start of the output? ...

It looks like everything is running smoothly, but it seems like the ReactDOM.render() method is missing in action

I'm currently diving into the world of React.js and eager to build my knowledge from the basics upwards. While delving into the documentation, I stumbled upon the utilization of ReactDOM.render(element, Document.getElementById("root")), whi ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...