Sorting Dates in Angular 4 Using an Array

I am struggling with sorting an array of Dates in Angular 4. My goal is to arrange my Customer array based on the value of releaseDate. This is what I currently have:

Inside the customer.component.ts file :

sort() {
    this.customers.sort((a: Customer, b: Customer) =>
      new Date(a.releaseDate).getTime() - new Date (b.releaseDate).getTime());
  }

I would like to call this method by clicking a button in the customer.component.html file:

<button (click)="sort()"> Sort</button>
<li *ngFor="let customer of customers">
  {{customer.releaseDate}}
</li>

However, when I click the button, nothing happens. The Array remains unchanged and no error message is displayed.

Is there something that I am missing? Can anyone provide assistance?

Answer №1

Your current syntax appears to be correct and is being utilized as intended.

For a practical demonstration of your code in action, take a look at this live example.

The issue may stem from the specific value assigned to the variable releaseDate when creating the Date object. Have you checked the console output within the sort function?

Answer №2

I have made updates to the plunker created by @JeanPaul A, where I addressed the issue of updating the array itself rather than the objects inside the array. You can view the changes in the updated plunker. The sorting functionality now works correctly for the objects within the array.

If there are still discrepancies in your data, I recommend checking the DatePipe formatting that I added. This will help you verify the accuracy of the dates displayed in the UI.

Updated Plunker Code:

// Angular app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { DatePipe } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="sort()">Sort</button>
      <ul>
         <li *ngFor="let date of dates">{{date | date: 'dd MM yyyy'}}</li>
      </ul>
      <ul>
         <li *ngFor="let customer of customers">
         {{customer.name}} -
         {{customer.releaseDate | date: 'dd MM yyyy'}}</li>
      </ul>      
    </div>
  `,
})
export class App {
  name:string;

  customers: Array<any> = [
    {"name": 'Mickey', "releaseDate": new Date('2012-07-12')},
    {"name": 'Minnie', "releaseDate": new Date('2013-07-12')},
    {"name": 'Donald', "releaseDate": new Date('2010-07-12')},
    {"name": 'Pluto', "releaseDate": new Date('2014-07-12')}
    ]

  dates:Array<Date> = [
    new Date('2012-07-12'),
    new Date('2013-07-12'),
    new Date('2010-07-12'),
    new Date('2014-07-12')
  ];
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  sort() {
    this.dates.sort((a:Date, b:Date) => new Date(a).getTime() - new Date (b).getTime());
    this.customers.sort((a: Customer, b: Customer) =>
      new Date(a.releaseDate).getTime() - new Date (b.releaseDate).getTime());
    console.log(this.customers);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

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 6 - Setting up radio buttons with Bootstraps

I am currently implementing Bootstrap's radio buttons functionality in my Angular 6 project. When using a button group, the active state should switch to the clicked button every time a different button is clicked. If this is confusing to understand, ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

Unlock the power of Angular ViewChildren to access and manipulate SVG elements efficiently

I have an SVG file loaded as an object: <object data="assets/img/states.svg" type="image/svg+xml" id="map"></object> This SVG includes a large PNG map along with several rect and text elements. <rect y="224.72084" x="644.87109" ...

Handling errors in nested asynchronous functions in an express.js environment

I am currently developing a microservice that sends messages to users for phone number verification. My focus is on the part of the microservice where sending a message with the correct verification code will trigger the addition of the user's phone n ...

Resetting the value of a radio button input option to null using Angular2 ngModel

In my Angular2 application, I am attempting to implement radio button inputs using ngModel and value. The goal is to have three options: true, false, and null. However, I am struggling to assign a value of null to one of the inputs. Ideally, when nothing ...

Is there a way to retrieve a data type from a class in TypeScript?

Within my code, there exists a class: class Person { name: string; age: number; gender: string; constructor(params: any){ this.name = params.name; this.age = params.age; this.gender = params.gender; } } My question is how ca ...

Utilizing Bootstrap.css in various Angular modules

Is there a way to utilize bootstrap.css in specific modules rather than applying it to the entire application? I wish to avoid adding Bootstrap.css to index.html or styles of angular.json, and only use it in certain modules. In my project, I have two dis ...

How can @ngrx be utilized to retrieve data based on the route?

Our webapp requires users to click through lists to reach a specific edit view. For example, starting from the landing page, a user selects a client, then an agent, and finally reaches the edit view of that agent. The URL in this scenario would contain the ...

What are some effective techniques for handling asynchronous operations while utilizing [displayWith] in an autocomplete

In my angular reactive form, I am struggling with an autocomplete functionality. I want to show the name (myObject.name) but use the ID (myObject.id) as the value. However, when the form is populated with existing values, there is a delay in retrieving th ...

Encountering an error in Angular2 and TypeScript: TS2322 error message stating that the type 'Response' cannot be assigned to type 'UserStatus'

Currently, I am facing some challenges while working with Angular2 and TypeScript. Transitioning from AngularJS to Angular2 has proven to be a bit tricky for me. To better understand this new framework, I decided to create an experimental app with the foll ...

Sending data from app.config file to component

I have a function in my app.config file that retrieves the current environment using window.location.hostname. I am looking for a way to pass this value to another component within my application. How can I accomplish this? Here is an excerpt from my app. ...

The primary export is not a React Component on the specified page: "/"

Encountering an error while attempting to use compiled code from Typescript to Javascript with Next.js Error message: The default export is not a React Component in page: "/" Seeking assistance on how to resolve this issue. Any help would be greatly appr ...

Require users to sign in immediately upon landing on the homepage in Next JS version 13 or 14

I have created a traditional dashboard application using Next.js 13 with a pages router that places all pages behind the /dashboard route, such as /dashboard/users, /dashboard/orders, and so on. I want to ensure that when a user visits the website, a fork ...

The state of an Angular 4 component

I am currently working on an Angular 4 application that consists of two components, CompA and CompB. CompA fetches books using an http service and displays them in a table, while CompB shows static data. When navigating between these components, I notice ...

Issue with the height not being updated in a parent React nested Accordion

Currently, I am in the process of developing the mobile version of my homepage. However, there seems to be a bug in my nested accordion labeled "Projects." The bug is causing an issue where the bottom projects section does not display at the correct height ...

Encountering an error with 'ng serve' on a recently established Angular project

After installing nodejs and Angular on my Windows 11 machine, I created a project using the ng new command. However, when I tried to run it with ng serve, I encountered the following error: c:\working\projects\xxxxxxx\xxxxxx-site>ng ...

Angular application encountering a 401 unauthorized error when attempting to connect to TFS API

Having trouble with an API get request in my initial Angular project. I'm attempting to retrieve all projects from a server using the correct URL (which works in Postman and my browser), as well as a token generated from my TFS account. Despite this, ...

Visual Verification

I'm currently working on a NestJS application that serves images with authentication requirements. I have implemented JWT for authentication, but I encountered an issue when trying to display the image in an img tag because I cannot attach the Authori ...

Is there a method for converting an Angular2 component into a string format?

Is it possible to leverage Angular2 template syntax when creating a Google Maps InfoWindow? My understanding is that this involves passing a component as a template string to the content property in the constructor object of the InfoWindow. If my assumpt ...

I am encountering a CORS error in Nest.js despite having CORS enabled

I'm currently working on a project using next.js for the frontend and nest.js for the backend. Despite having CORS enabled in my main.ts file of nest.js, I keep encountering CORS errors. Below is an excerpt from my main.ts file: import { NestFac ...