如何查看模板中的当前日期?

时间:2017-01-21 21:58:08

标签: angular typescript

我的组件中有一个带时间戳的对象。

我尝试做的是在模板中检查运行时的时间戳。 例如,显示用户的在线状态..如果在线我显示绿点,否则它应该在运行时切换到红点。

<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>

有人有想法吗? :)

1 个答案:

答案 0 :(得分:4)

我认为更好的方法是在组件中创建一个计时器,如

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将在每秒后更新,您可以在模板中更轻松地使用它进行比较,例如

<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>