Reputation: 226
I'm new to front-end development and Angular2.
I'm writing an app where I'm given a fromDate and an endDate, and the app needs to display the date range. For example, fromDate = '10/02/2016' endDate = '11/02/2016'
, the app will display the date range as: 10-11 Feb 2016, and this date range format may change in the future (also need to consider the cases where months or years are different of course).
My thought is to use chaining pipes: {{ dateArray | date: 'dd/MM/yyyy' | rangeDate}}
where dateArray = [fromDate, endDate]
and I hope {{ dateArray | date: 'dd/MM/yyyy'}}
can return two formatted date strings (in an array) so I can then use my custom pipe I create:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'dateRange'})
export class DateRangePipe implements PipeTransform {
transform(value: string[], args: any[]) {
return "desired output";
}
}
to easily manipulate with the two strings two get the desired output.
But this is wrong because Angular 2 Date Pipe cannot transfer more than one date value to string and it's return type is string
, not string[]
.
So I was wondering if there is a way to write a for-loop-like thing in HTML to achieve this task. Like, it takes a date[]
, and send each of its item to the date pipe, and combine the results into a string[]
and send it to dateRange pipe.
Upvotes: 2
Views: 3133
Reputation: 56
What you need is a date pipe that receives an array of dates, I did this and it worked for me:
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({
name: 'rangeDate'
})
export class RangeDatePipe implements PipeTransform {
transform(rangeDates: any, args?: any): any {
if (rangeDates) {
const range = rangeDates.map(d => moment(d).format('DD/MM/YYYY'));
return range[0] + ' - ' + range[1];
} else {
return null;
}
}
}
You can pass an array of dates to the pipe like: [new Date(), new Date()].
Upvotes: 0
Reputation: 4794
The date
pipe will not help you here because: a) as you've already figured it out date pipe does not take an array as an input; b) you have special requirements to translate two dates into something that is a actually mixed parts of their representation which the date pipe have no idea about how to do it.
You need to implement your own dateRange
pipe (kind of what you're trying) which would take an array of dates and yield single string formatted as you wish as an output.
Upvotes: 1