How can you arrange a table based on date columns using Angular 6?

My table has two columns: insdate and resdate, both containing date data. I am looking to sort the table based on these columns. For instance, when a user clicks the resdate column, I want to be able to sort it in either increasing or decreasing order.

I attempted something similar to what is shown in this tutorial.

The data is retrieved as JSON from a webservice, with dates being returned as strings. Here's an example of the data returned:


logs = [
    { insdate: '11.12.2018 06:41:25', resdate: '11.12.2018 06:41:26' },
    { insdate: '10.12.2018 06:42:24 ', resdate: '10.12.2018 06:42:24' },
    { insdate: '10.12.2018 06:42:29', resdate: '10.12.2018 06:42:29'},
    { insdate: '12.12.2018 06:45:00', resdate: '12.12.2018 06:45:00' },
    { insdate: '11.12.2018 06:45:47', resdate: '11.12.2018 06:45:47' },
    { insdate: '10.12.2018 06:46:42', resdate: '10.12.2018 06:46:42' },
    { insdate: '10.12.2018 06:46:42', resdate: '' },
    { insdate: '', resdate: '12.12.2018 07:16:50' },
];

The date format is dd.MM.yyyy HH:mm:ss, and results are ordered by insdate on the server side. It is important to note that insdate and resdate may have empty values.

In my application, I have defined:

<th (click)="sortType('resdate')" [class.active]="sortBy==='resdate' ">ResDate</th>

in my app.component.html file.

In the app.component.ts file, I have implemented the following function:


sortType(sort: string)
{
    this.copyLogs=this.logs;
    if(sort==='resdate'){
        this.logs=this.copyLogs.sort(this.sortByResDate);
    }   
}

sortByResDate(r1: any, r2:any){
    let d1=moment(r1.resdate, 'dd.MM.yyyy HH:mm:ss').unix();
    let d2 = moment(r2.resdate, 'dd.MM.yyyy HH:mm:ss').unix();

    if(d1>d2) {
        return 1;
    }
    else if(d1===d2) {
        return 0;
    }
    else return -1; 
}

Even though I used Unix time for comparison due to the dates being strings, the sorting did not turn out as expected. While the functions are being accessed and sorting is working, it is not correct :).

If anyone can point out where I might be going wrong, I would greatly appreciate it!

Answer №1

I managed to achieve success without relying on moment(). Instead, I utilized new Date()</ along with getTime(), which proved to be effective. The key lies in deciding whether you want the empty resdate to appear at the beginning or end of the table.

Update

Unfortunately, the previous solution failed to work properly when using the format dd:mm:yyyy HH:mm:ss. However, a new approach involving moment() has been implemented successfully: https://stackblitz.com/edit/angular-x3vdpq
P.S. If you encounter issues with import moment, consider adding

"allowSyntheticDefaultImports": true
in the compilerOptions within your tsconfig.json, and then proceed by using the following syntax:

import moment from 'moment';

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

Angular2: Filtering an array based on the presence of items in another array

Looking to selectively filter out entries from an object array based on certain id values within another array. I've experimented with different methods but haven't found a solution that works yet. List of id´s: list = [1,3] Array to be filte ...

Guide on linking a trust policy to an IAM role through CDK

{ "Version": "2008-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": [ ...

Navigating the root path that is defined in the gulp task within an Angular application

My current task involves building my application with the following code: const app = new Metalsmith(config.styleguide.path.root); app.use( msDefine({ production: false, rootPath: '/' }) ); app.use( ms ...

Angular - Eliminate module during build process

In my current project, there is a module called data-generator that is only used during development mode (when running `npm start`). When building the application (using `npm run build`), this module is not needed. Is there a way to exclude it from the pro ...

What is the best way to invoke a function using a string as its name?

In my grid configuration function, I am assigning column definitions. One key, valueGetter, requires a function to be called to fetch the column value. The issue I am encountering is that the API returns this value as a string. When I try to set it using ...

I am encountering difficulties when attempting to install a specific Angular project using npm install

My old laptop was able to run my Angular project smoothly, but now I'm encountering numerous errors when trying to install it with npm on a new device. Any assistance based on the attached log would be greatly appreciated. Thank you in advance. shiva ...

Encountering a problem where the alert popup does not appear when refreshing Chrome for the first time on the homepage in an Angular application

Firstly, I want to express my gratitude for your response to my previous inquiry. I am currently encountering an issue. When landing on the homepage for the first time, the alert popup does not work. However, once inside the application, it functions prop ...

Issue with uploading video files using ng2-file-upload in Angular7 and ASP .Net Core 2.1

While working on my project, I encountered an issue with uploading video files using ng2-file-upload to the server. The photo upload functionality is working fine, but when attempting to upload a video file larger than 27MB, the process gets canceled autom ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Prohibit the Use of Indexable Types in TypeScript

I have been trying to locate a tslint rule in the tslint.yml file that can identify and flag any usage of Indexable Types (such as { [key: string] : string }) in favor of TypeScript Records (e.g. Record<string, string>). However, I haven't had a ...

Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface. export interface fooParent { appId: string, appName: string } export interface fooDetail { childTitle: fooParent. ...

The onClick event handler is functioning properly, but the ngOnInit() lifecycle method is not executing the function as

I have created a filter function that is applied to elements in a list. It works when I use it on the page with a click event, like this: <button (click)="FilterFn5()"> do </button> However, it does not work when I put the function i ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Using Angular 4 and harnessing the power of RxJS for advanced

Attempting to wrap my mind around RxJS has led me to a question. To gain a deeper understanding of its workings, I initiated a new Angular 4 application created with Angular CLI. Within this environment, I have executed the following code: this.http.get ...

How to troubleshoot: trying to assign '{ source: string; }' to type 'string' is not valid

I'm encountering an issue that seems like it should have a simple solution, but I can't seem to find any explanations on how to fix it. I'm working with Next.js and Typescript to create a component that displays an image and uses hooks to ma ...

"Utilize PrimeNG's p-tabpanel to bind a unique style class to

When using the tabview component from PrimeNG, I am encountering an issue where I am unable to bind a header style class. Here is my static HTML code that works: <p-tabPanel header="Title" headerStyleClass="badge" formGroupName=&quo ...

Deploying an Angular application on Kubernetes Ingress with a custom path instead of the root path

My Angular application runs smoothly in the development environment. However, when I attempt to deploy it to a Kubernetes cluster and set up an ingress route for it, things do not function as expected. Specifically, I have configured the following ingress ...

Tips for selecting a button in Angular 2?

Is there a way for the JavaScript of a component to click an HTML button without Jquery? Most documentation usually covers handling a button that is on the page, but in this case, it is part of an element with ngNoForm, which is handled by the browser it ...

Updating the position of an element in HTML is not possible

For my webpage, I am attempting to adjust the position of all images that are displayed. Despite trying to change the position of a single image using the DOM method, I have run into a problem where the position does not update as expected. Although the co ...

Condition for rendering child components using Angular guard

I am faced with a scenario where I have 3 children in a parent component and I need to render them based on specific conditions: If my variable is equal to zero, the welcomePage should be rendered If the variable falls between one and ten, then the interm ...