Angular 13 ng-bootstrap date field sortable table

I need help sorting an Observable Array with Date datatype using the Sort() method in Angular 13. You can find an example at: https://stackblitz.com/edit/ngbootstrap-table-sorting-aabk9h?file=app%2Ftable-sortable.ts

Here is my table-sortable.html:

<ng-container *ngIf="countriesListAll$ | async as countries">
<table class="table table-striped">
  <thead>
  <tr>
    <th scope="col">#</th>
    <th scope="col" sortable="name" (sort)="onSort($event)">Country</th>
    <th scope="col" sortable="area" (sort)="onSort($event)">Area</th>
    <th scope="col" sortable="datewithtime" (sort)="onSort($event)">Dates celebrated</th>
    <th scope="col" sortable="population" (sort)="onSort($event)">Population</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let country of countries">
    <th scope="row">{{ country.id }}</th>
    <td>
      <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="me-2" style="width: 20px">
      {{ country.name }}
    </td>
    <td>{{ country.area | number }}</td>
    <td>{{ country.datewithtime }}</td>
    <td>{{ country.population | number }}</td>
  </tr>
  </tbody>
</table>
</ng-container>

The main difference from the provided example is that I receive the list of countries from the countriesList$ observable.

My table-sortable.ts:

import { Component, Directive, EventEmitter, Input, Output, QueryList, ViewChildren } from '@angular/core';

interface Country {
  id: number;
  name: string;
  flag: string;
  area: number;
  datewithtime: Date;
  population: number;
}

export type SortColumn = keyof Country | '';
export type SortDirection = 'asc' | 'desc' | '';
const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' };

const compare = (v1: string | number, v2: string | number) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0;

// Rest of the code remains unchanged...

@ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

onSort({column, direction}: SortEvent) {

    // resetting other headers
    this.headers.forEach(header => {
      if (header.sortable !== column) {
        header.direction = '';
      }
    });

    // sorting countries
    if (direction === '' || column === '') {
      this.countriesListAll$= this.countriesListAll$;
    } else {
      this.countriesListAll$ = this.countriesListAll$.pipe(map(data => data.sort((a, b) => {
    const res = compare(a[column], b[column]);
    return direction === "asc" ? res : -res;
  })));
    }
  }

}

I am having difficulties sorting the Date field with time included like this format: 21-DEC-2020 14:10:00. How can I properly sort this field?

Answer №1

To solve the issue, make sure to modify the comparison section:

const compareValues = (val1: string | number | Date, val2: string | number | Date) => ( val1 < val2 ? -1 : val1 > val2 ? 1 : 0);

(for those who may require assistance with this)

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

Angular: Intercepting an HttpResponse to trigger additional calls before passing the response back to the caller

My current objective is to intercept a response and, if a certain value (CHALLENGE) is present, trigger a call to another API. I need to retry this process 3 times if necessary. Upon success, I should respond to the initial call and pass the result back to ...

Creating a Search Bar with Ionic 3, PHP, and SQL Server for Efficient Data Retrieval

I have a project in progress that involves using Ionic 3, PHP, and a SQL Server database for the backend. One of the features I'm trying to implement is a search bar. I've looked at various examples online, but none of them have worked for me. Co ...

The power of Storybook and NX combined: One central Storybook instance to rule them all projects

I am managing a collection of 7 angular apps within an nx monorepo, each utilizing visual components stored in a shared-ui lib. My goal is to set up a new project with Storybook where I can automatically generate stories for all these visual components. Th ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Steps to authorize an API request using a token

I have an API that requires authentication using a token. In Swagger UI, I am able to authenticate this API by providing the token in the authorize section. For example, if I input "Token 6ec8f4023d8148209749a1ed972xxxx" in the authorization box Here is ...

Best practice for integrating Typescript into an established ASP.NET 4 Webforms project

Currently, I am working on an older asp.net 4.0 Webforms project using Visual Studio 2015. My goal is to transition from using Javascript to TypeScript for certain client side code tasks. While I have experience using TypeScript in projects outside of Vis ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

Encountering an error while using TypeScript, Mocha, and Express: "TypeError: app.address is not a

While transitioning an API from ES6 to TypeScript, a particular issue arises when attempting to run unit tests on the Express REST Endpoints: TypeError: Cannot read property 'address' of undefined The server code has been slightly adjusted for ...

The server on Localhost:3000 encountered an issue with a middleware error while attempting to utilize the upload feature with Dropbox

I've encountered an issue that I'm struggling to fix. The only solution I found for resolving errors in this file was the following: import { clerkMiddleware } from '@clerk/nextjs/server'; import { NextResponse } from 'next/server& ...

How to enable Access-Control-Allow-Origin for Angular 5 on the client side

I am currently utilizing the httpClient Angular package to make GET requests. The URL I am using to fetch data is , but I am encountering a CORS error in the console. Unfortunately, I do not have access to the server side code, but I still want to enable ...

Questions on deploying Angular2 to a production environment

Here are some queries regarding transitioning an angular2 web project to a production environment: While development is done on a lite server, what would be the ideal choice for production? Would another server module of nodejs be better? Considering t ...

Angular 8's cutting-edge feature: the dynamic password validator

Hello, I have an API that returns an array object called passwordPolicy with the following properties: PasswordMinLength: 6 passwordMinLowerCase: 1 passwordMinNumber: 1 passwordMinSymbol: 0 passwordMinUpperCase: 1 The values of these properties can change ...

Assign the private members of the class to the arguments of the constructor

class Bar { #one #two #three #four #five #six #seven #eight #nine #ten #eleven #twelve #thirteen #fourteen #fifteen #sixteen constructor( one, two, three, four, five, six, seven, eight, ...

Issue with uploading files due to cross-domain restrictions in AngularJS and Web API

Having trouble uploading a CSV file from Angular using POST to a Web API endpoint, resulting in the following error: "XMLHttpRequest cannot load http://localhost:89/WebService/Upload. No 'Access-Control-Allow-Origin' header is present on the ...

Angular 4 Templates in Visual Studio 2017

Seeking recommendations for an Angular 4 template that is compatible with Visual Studio 2017. Any suggestions on the optimal template to utilize and recommended steps to follow? This project will involve creating a single-page application using Angular 4 ...

Angular is patiently awaiting the response from the REST API in the subscribe method

I am facing an issue with my REST API call on the client side (Angular). When I subscribe to it, the function continues running without waiting for a response. Can someone please help me figure out how to hold the function until the response is received? G ...

The input element's value property updates only once

Whenever I input a number greater than 1 into the input field, the value automatically changes to 1 due to validation. Oddly enough, this only seems to work for the first number entered. For example, if I type in 11, the input value remains as it is instea ...

Determine the generic parameter of the output type by analyzing the resolved value of a data type within the function

I am looking to automatically determine the generic parameter of the return type by utilizing the resolved value of a type within the function. Consider the following: export type Context = any; export type Handler<T> = (ctx: Context) => Promise& ...

Display the information in real-time as it is being transmitted to the backend

I'm facing a challenge with the user experience. Currently, I am developing a chat application using Ionic, Angular, and Firebase. The issue at hand is that messages are only displayed once they are successfully sent to the server. This means that o ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...