如何在打字稿中获得给定时间和当前时间的差异是

时间:2018-11-14 11:50:40

标签: angular typescript date angular7

我使用的是角度7,如果满足以下条件:给定时间早于当前时间,我想在html组件中显示元素。

我尝试了以下逻辑

 getTimeDiff(time, date)
    {

         const dateNow = new Date()
         const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

         const diff = Math.abs(Math.abs(dateNow.getTime() - slotDate.getTime()) /  3600000)

        //if diff is not negative
       if(diff) {
         return false
      } 
        else {
         return true
       }
     }

HTML

<span *ngIf="getTimeDiff(result.endtime, result.date)"> open </span>

更新

使用* ngFor显示元素,因此我无法在ngOnInit()中调用getTimeDiff。

<div *ngFor="let result of results">
    <span *ngIf="getTimeDiff(result.endtime, result.date)"> open </span>
</div>

但是由于某种原因,我得到了:

  

ViewAppointmentsComponent.html:30错误错误:   ExpressionChangedAfterItHasBeenCheckedError:表达式已更改   经过检查后。先前的值:'null:6.0732225'。当前   值:“空:6.0732252777777775”。

2 个答案:

答案 0 :(得分:1)

Angular运行更改检测,当它发现已传递给子组件的某些值已更改时,Angular会引发错误ExpressionChangedAfterItHasBeenCheckedError

最好创建一个变量来保存信息,而不是在每次更改检测时都调用相同的函数

different = false;  //<-- hold the difference state.

getTimeDiff(time, date)
{

     const dateNow = new Date()
     const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(dateNow.getTime() - slotDate.getTime()) /  3600000)

    //if diff is not negative
   if(diff) {
     this.different = false  //<-- change to false.
  } 
    else {
     this.different  = true  //<-- change to true.
   }
 }

html

<span *ngIf="different"> open </span>
  

注意:如果要获取一次,请不要忘记在ngOnInit等适当的位置调用getTimeDiff函数。

答案 1 :(得分:1)

这是一个生命周期错误,表示Angular已经检查了一个值,但是由于某种原因您正在更新它。

如果在功能中加入控制台日志,您会看到它被称为很多的时间。

这是因为绑定到指令的函数在每次用户交互时都会被调用。

这意味着每次调用它都会获得一个新的日期值(+1 ms)

为避免这种情况,请在创建组件时创建日期并进行比较。如果需要,可以在一段时间内更新它,但不能在函数本身中更新。

constructor(private now = new Date()) {}

getTimeDiff(time, date)
{
     const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(this.now.getTime() - slotDate.getTime()) /  3600000)

    //if diff is not negative
   if(diff) {
     return false
  } 
    else {
     return true
   }
 }

编辑

为避免调用函数,可以使用在更改时更新的变量:

this.timeDiff: boolean;

ngDoCheck() {
  this.timeDiff(this.result.endtime, this.result.date);
}

getTimeDiff(time, date)
{
     const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(this.now.getTime() - slotDate.getTime()) /  3600000)

    //if diff is not negative
   if(diff) {
     this.timeDiff = false;
  } 
    else {
     this.timeDiff =  true;
   }
 }

在您的HTML

<span *ngIf="timeDiff"> open </span>

ngDoCheck是生命周期挂钩(例如ngOnInit),可以由

总结
  

检测Angular无法跟踪的更改的功能