Im trying to create a pipe that takes a date time stamp and returns how long it has been since that time.
I have the following pipe which returns the duration once, but I need this pipe to increment every second to give a timer effect:
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({ name: 'duration' })
export class DurationPipe implements PipeTransform{
transform(value: any){
var now = moment(new Date());
var end = moment(value);
var dif = moment.duration(now.diff(end));
var toReturn = [];
if(("00" + dif.hours()).slice(-2) != "00"){
toReturn[toReturn.length] = ("00" + dif.hours()).slice(-2);
}
toReturn[toReturn.length] = ("00" + dif.minutes()).slice(-2);
toReturn[toReturn.length] = ("00" + dif.seconds()).slice(-2);
return toReturn.join(':');
}
}
I've looked at the async pipe but I cant seem to get it working how I desire.
Any solutions?
The Pipe component pass value from the template and transform a new value out. You shouldn't use Pipe to calculate a time duration and update to the view periodically because Pipe won't update itself unless value changed. ( Pipes are all pure pipe by default! )
I think you should implement this into your component instead of implement this in Pipe.