first, this is what I would like to accomplish:
Let's say I have a model for a posting that contains a js Date object. Now, I would like to render the date in a custom, human readable format that does not show a date and time, but rather an offset from now (i.e. "just now", "about one hour ago", "about two hours ago" etc.).
I am new to both, TypeScript and angular2, but from what I read so far, the most elegant approach would be to use a custom pipe like that:
@Pipe({name: 'hrTime'})
export class HrTimePipe implements PipeTransform {
constructor(private translate: TranslateService) {
}
transform(val: Date): string {
// Roughly check if that date is about one hour ago
let now: Date = new Date();
now.setMinutes(now.getMinutes() - 90);
if (val > now) {
return this.translate.instant("about_1_h_ago");
}
}
}
The problem with this approach is that TranslateService's instant()
method doesn't make sure the translation file is loaded at the time this pipe is constructed or used. Therefore, my custom pipe currently just returns my translation key (since instant()
doesn't find my translation).
For larger timegaps (i.e. more than a day ago), my pipe should internally just use the date format pipe, so returning a translation key that has to be piped into translate
isn't really an option.
Do you have any suggestions? Is using a custom pipe the right approach for what I would like to accomplish?
Thanks!