Issue
I have got a problem regarding sorting an array of Dates in Angular 4. I want to order my Customer
array by the value releaseDate
. So this is what I have right now:
In the customer.component.ts
:
sort() {
this.customers.sort((a: Customer, b: Customer) =>
new Date(a.releaseDate).getTime() - new Date (b.releaseDate).getTime());
}
I want to trigger this method by clicking on a button in customer.component.html
:
<button (click)="sort()"> Sort</button>
<li *ngFor="let customer of customers">
{{customer.releaseDate}}
</li>
When I click the button nothing happens. The Array stays the same and I also don't get an error message.
Am I missing something? Can anyone help?
Solution
I updated the plunker that @JeanPaul A created so you can see the difference. In his plunker he is updating the array itself, not objects inside the array, so I think it needed updating.
If you look at the new plunker you can see the difference, but it does work, sorting the objects inside the array. I think there must be something wrong with your data. I added the DatePipe to format the dates so you can use this to easily see in the UI that your dates are correct.
Plunkr Code:
//our root 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 {}
Answered By - rmcsharry
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.