Reputation: 681
I have an object with a timestamp in my component.
What I try to do is to check the timestamp at runtime in the template. for example to show the user online status of a member.. if online I show a green dot, else it should switch to a red dot live during runtime.
<div class="show_member_line">
{{member.membername}}
<div *ngIf="member.lastactivity > ( !!!new Date().getTime()!!! - 120 )" class="status_online"></div>
<div *ngIf="member.lastactivity < ( !!!new Date().getTime()!!! - 120 )" class="status_offline"></div>
</div>
anybody have an idea? :)
Upvotes: 3
Views: 9643
Reputation: 3867
Better approach in my opinion would be to create a timer in your component like
import {Component, OnInit, OnDestroy} from '@angular/core';
private timerSubscription: any = null;
private lastActivityTime: Date;
ngOnInit(){
let timer = Observable.timer(1000, 1000);
this.timerSubscription = timer.subscribe((t:any) => {
this.timerExecuted();
});
}
private timerExecuted(): void {
var currentDate = new Date();
currentDate.setHours(currentDate.getHours() - 2); //subtract 2 hours or 120 minutes from current date
this.lastActivityTime = currentDate;
}
ngOnDestroy() {
//unsubscribe the subscription in ngDestroy
if (this.timerSubscription != null)
this.timerSubscription.unsubscribe();
}
lastActivityTime will be updated after each second and you can use it for comparison more easily in your template like
<div class="show_member_line">
{{member.membername}}
<div *ngIf="member.lastactivity > lastActivityTime" class="status_online"></div>
<div *ngIf="member.lastactivity < lastActivityTime" class="status_offline"></div>
</div>
Upvotes: 4