Having trouble organizing the date strings in the material table column

In my Angular application, I have a material table with multiple columns that I am sorting using matSort. While I can successfully sort the last two columns in ascending or descending order, I am facing an issue with the first column which contains date values. The problem is that I can only sort the date column once and subsequent attempts to sort it again do not work.

I attempted to override the sortingDataAccessor property on MatTableDataSource but it did not resolve the issue:

    this.dataSource.sortingDataAccessor = (item, property) => {
      switch (property) {
        case 'day': return new Date(item.day);
        default: return item[property];
      }
    };
    this.dataSource.sort = this.sort;
  }

Here is the section of code in my trips.component.html file where the date (day) column is defined within the material table:

<div class="table-responsive">
<table class="table table-bordered>
  <mat-table [dataSource]="dataSource" matSort>

    <!-- Day column -->
  <ng-container matColumnDef="day">
    <mat-header-cell *matHeaderCellDef mat-sort-header>Day</mat-header-cell> 
    <mat-cell *matCellDef="let trip">{{ trip.start | date: 'dd/MM/yyyy' }}</mat-cell>
  </ng-container>

This snippet reflects the structure in my trips.component.ts file:

import { Component, OnInit, ViewChild } from '@angular/core';
import { Trip } from 'src/app/models/Trip';
import { MatSort, MatSortable, MatTableDataSource } from '@angular/material';
import { DataSource } from '@angular/cdk/collections';

@Component({
  selector: 'app-trips',
  templateUrl: './trips.component.html',
  styleUrls: ['./trips.component.css']
})
export class TripsComponent implements OnInit {

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

private trips: Trip[];
displayedColumns = ['day', 'time', 'duration', 'from', 'to', 'mileage', 'cost'];
dataSource;

constructor() {
  this.trips = [new Trip("12/11/2019 02:30:15", "12/11/2019 06:04:43", "Landsmeer", "Amsterdam-West", 1.97, 1.06), new Trip("0 8/29/2019 16:10:14", "08/29/2019 18:19:54", "Amsterdam-West", "Vlaggemast", 14.74, 9.20),new Trip("08/16/2019 01:56:42", "08/16/2019 03:23:26", "Amsterdam-Zuid", "Amsterdam-Noord", 7.88, 7.61), new Trip("03/25/2019 04:01:27", "03/25/2019 09:58:27", "NDSM-Plein", "Amsterdam-Zuid", 5.49, 5.01), new Trip("12/23/2018 14:27:06", "12/23/2018 18:47:34", "Westpoort", "Schakelstraat", 2.00, 1.98), new Trip("12/10/2018 12:26:56", "12/23/2018 14:39:29", "Ijdok", "Amsterdam-Oost", 3.46, 2.47), new Trip("07/03/2018 11:20:39", "03/07/2018 12:37:51", "Amsterdam-Noord", "Huidekoperstraat", 7.66, 5.22), new Trip("05/19/2018 22:41:39", "05/20/2018 03:29:20", "Amsterdam Nieuw-West", "Amsterdam-Centrum", 13.32, 6.93), new Trip("04/21/2018 08:37:04", "04/21/2018 15:24:38", "Buiksloterweg", "Amsterdam-Noord", 13.72, 13.13)
   ]
  }

  ngAfterViewInit(){
    this.dataSource.sortingDataAccessor = (item, property) => {
      switch (property) {
        case 'day': return new Date(item.day);
        default: return item[property];
      }
    };
    this.dataSource.sort = this.sort;
  }

  ngOnInit() {

    this.dataSource = new MatTableDataSource(this.trips);

}

}

Any assistance on resolving this sorting issue would be greatly appreciated.

Answer №1

If you're encountering sorting issues, consider setting the property directly on the component's root level instead of inserting code into a method. Take a look at the example below for guidance:

  private sort: MatSort;
  // Essential for enabling sorting on Mat tables.
  @ViewChild(MatSort) set matSort(ms: MatSort) {
    this.sort = ms;
    this.dataSource.sort = this.sort;
    this.dataSource.sortingDataAccessor = (data, header) => {
      switch (header) {
        case 'day': return new Date(data.day);
        default: return data[header];
      }
    };
  }

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

Searching for several arrays in Angular

Hello everyone, I have an API that returns data like this: [ [{ "id": 1, "qte": 12, "date_creation": "2020-08-17T00:00:00+02:00", "date_update": "2020-08-17T00:00:00 ...

Retrieve the implementation of an interface method directly from the constructor of the class that implements it

I am looking to create a function that takes a string and another function as arguments and returns a string: interface Foo { ConditionalColor(color: string, condition: (arg: any) => boolean): string; } I attempted to pass the ConditionalColor metho ...

Potential keys + keys that are present in the `initialData`

Is there a way to specify the type of data in order to include all keys that exist in initialData plus additional keys from Item as Partial(optional)? class TrackedInstance<Item extends Record<string, any>, InitialData extends Partial<Item> ...

Collaborative input within configuration elements of components (syntax for configuring components)

My component is quite complex with numerous **@Input()**s and for better organization, I wish to group the inputs similar to how DexExtreme's grids do. The way DevExtreme grids handle their Inputs is by separating them like this: <dx-data-grid ...

The resolver function in the Nextjs higher order API is not defined

I am trying to create a custom wrapper function for my NextJs API routes that will verify a JWT in the request, validate it, and then execute the original API handler. Here is how I have defined my wrapper function: interface ApiError { message: string, ...

Explicit final argument in TypeScript

Is it feasible to define a function in TypeScript 2.7.2 and above with variable parameters, but ensuring that the final parameter has a specific type? I am attempting to craft an ambient TypeScript declaration for a JavaScript library that utilizes functi ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

Angular 2 setting a class property to the output

There seems to be an issue with logging to the console in my getProfile() method. When I assign this.user to user, it does not return my json object as expected. If I write the following code: getProfile() { this.userService.getPortInfo() .th ...

retrieving information from an array nested within a JSON object in an Angular application

I am struggling to retrieve two specific values from a JSON object. The content of the JSON is as follows: [ { "type":"session_start", "properties":[ { "property":"activity&q ...

Testing the subscribe function in Angular within a returned Promise: A guide

I am facing an issue with a service that returns a Promise. It retrieves data from a JSON file using a subscribe method before resolving the Promise. I am trying to test the result of this Promise based on the parameters I provide, but I am encountering t ...

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...

Encountering Error 404 while submitting a form on Prisma, Axios, and NestJS

Currently, I am working on a Sign Up page using SolidJs and NestJS with Prisma. However, when I try to submit the form, I encounter an error that says POST 404 (Not Found) and this error is also returned by axios. Additionally, my setup includes postgres ...

Retrieving information from a JSON API using Angular with Typescript

Currently, I am dealing with an API JSON to fetch a list of countries, followed by a list of states, and then cities within that state and country. The challenge lies in the second API call that I make. In the beginning, I load a list of continents and the ...

Whenever the route changes in Angular, the components are duplicated

Whenever I switch routes in my Angular application, such as going from home to settings and back to home, all the variables seem to be duplicated from the home page and are never destroyed. I noticed that I created a loop in the home component that displa ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Angular 5: Ensure Constructor Execution Occurs Prior to Injection

I am working with a file that contains global variables: @Injectable() export class Globals { public baseURL:string; public loginURL:string; public proxyURL:string; public servicesURL:string; constructor(platformLocation: PlatformLocation) { ...

Is there a way to disable a field or div in Angular 8 based on a user's role permission, rather than just showing or hiding it with ngx-per

<div *customPermissions="['USER']"> <div><input type="text" placeholder="testing custom permission"></input></div> </div> This code snippet displays a div based on custom p ...