ngx-moment
ngx-moment copied to clipboard
How to handle null values ?
Is theire a way to handle null values.
{{date | amTimeAgo}}
displays invalide date if date
is null
how customize that to something like --
+1
Is there any updates?
Hi! I really like this pipe and I was wondering if there was any momentum to change how the pipe handles null, nil, or undefined dateTime values. Thanks!
I'd love to hear a few suggestions so we can choose
if date is null just return a null, by default, or return a parameter like {{ date | amTimeAgo:'--' }}. timeAgo has static format, so it is enough to have only null value format parameter.
Any news on this? Would it be feasible to use the second parameter to define the default message for an invalid date?
That shouldn't be a breaking change, as the default message could still be Invalid date. I'm happy to work on an implementation, update the tests and send a PR for consideration.
{{someItem.dueToUtc ? (someItem.dueToUtc | amFromUtc | amLocal | amDateFormat:'LL') : 'your message'}}
Personally, I think we should add some condition the pipe to avoid condition on the template likes this pipe
export class DateFormatPipe implements PipeTransform {
transform(value: Date | moment.Moment | string | number, ...args: any[]): string {
if (!value) { return ''; }
return momentConstructor(value).format(args[0]);
}
}
Why not copy the logic of the standard angular pipes when it comes to null values... https://github.com/angular/angular/blob/master/packages/common/src/pipes/date_pipe.ts
transform(value: any, format = 'mediumDate', timezone?: string, locale?: string): string|null {
if (value == null || value === '' || value !== value) return null;
try {
return formatDate(value, format, locale || this.locale, timezone);
} catch (error) {
throw invalidPipeArgumentError(DatePipe, error.message);
}
}
How about Never
?
I suggest you to create a new Pipe extending the original one, with something like this :
import { Pipe, PipeTransform } from '@angular/core';
import moment from 'moment';
import { TimeAgoPipe } from 'ngx-moment';
@Pipe({
name: 'customTimeAgo'
})
export class CustomTimeAgoPipe extends TimeAgoPipe implements PipeTransform {
transform(value: moment.MomentInput, omitSuffix?: boolean, formatFn?: (m: moment.Moment) => string): string {
if (!value) {
return '-';
}
return super.transform(value, omitSuffix, formatFn);
}
}
... and use {{ myDate |customTimeAgo }}
in your html template