ngFor
上的代码
<div *ngFor="let date of tripdetail.trip_availabledate; let i = index;">
<a [ngClass]="{'active': date.status}" class="btn btn-block" (click)="keyPress('currentDateSelected', i)">{{date.start_date | date:'dd MMM yyyy'}} - {{date.end_date | date:'dd MMM yyyy'}}</a>
</div>
问题是,如何使用 ngFor
上的 startdates 对这些可用日期进行排序?
最佳答案
尝试这样:
在 Controller 中排序:
ngOnInit() {
this.tripdetail.trip_availabledate = this.tripdetail.trip_availabledate.sort((a: any, b: any) =>
new Date(a.start_date).getTime() - new Date(b.start_date).getTime()
);
}
您也可以使用管道尝试此操作。
使用管道排序
按日期管道排序:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortBydate'
})
export class SortBydatePipe implements PipeTransform {
transform(value: any, key?: any): any {
return value.sort(
(a: any, b: any) =>
new Date(a[key]).getTime() - new Date(b[key]).getTime()
);
}
}
模板:
<div *ngFor="let date of tripdetail.trip_availabledate | sortBydate : 'start_date'; let i = index;">
<a [ngClass]="{'active': date.status}" class="btn btn-block" (click)="keyPress('currentDateSelected', i)">{{date.start_date | date:'dd MMM yyyy'}} - {{date.end_date | date:'dd MMM yyyy'}}</a>
</div>
<强> Working Demo
关于angular - 在 ngFor Angular 上按 start_date 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499341/