I am trying to create a 'time ago' pipe for my Angular 2 application.
It should transform a date to a string such as '5 minutes ago' or '60 seconds ago'. It works nicely so far, but it doesn't update after the first calculation. If the given date is for example 5 seconds ago, it displays '5 seconds ago' but never changes after that.
I have already tried setting the pipes 'pure' value to false but that didn't help.
Here is my code:
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({
name: 'messageTime',
pure: false
})
export class MessageTimePipe implements PipeTransform {
transform(value: Date, []): string {
var result: string;
// current time
let now = new Date().getTime();
// time since message was sent in seconds
let delta = (now - value.getTime()) / 1000;
// format string
if (delta < 10) {
result = 'jetzt';
} else if (delta < 60) { // sent in last minute
result = 'vor ' + Math.floor(delta) + ' Sekunden';
} else if (delta < 3600) { // sent in last hour
result = 'vor ' + Math.floor(delta / 60) + ' Minuten';
} else if (delta < 86400) { // sent on last day
result = 'vor ' + Math.floor(delta / 3600) + ' Stunden';
} else { // sent more than one day ago
result = 'vor ' + Math.floor(delta / 86400) + ' Tagen';
}
return result;
}
}
I'm using the filter like this:
TypeScript:
import {Component, Input} from 'angular2/core';
import {MessageTimePipe} from '../../pipes/message-time.pipe';
@Component({
selector: 'message-item',
pipes: [MessageTimePipe],
templateUrl: 'build/components/message-item/message-item.component.html'
})
export class MessageItemComponent {
@Input()
message: JSON;
date: Date;
ngOnInit() {
this.date = new Date(2016, 3, 16, 12, 49, 10);
}
}
HTML:
<p class="time">
{{ date | messageTime }}
</p>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…