Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何对来自管道的数据应用条件_Angular_Typescript - Fatal编程技术网

Angular 如何对来自管道的数据应用条件

Angular 如何对来自管道的数据应用条件,angular,typescript,Angular,Typescript,我实现了一个管道,它获取两个值并查找它们之间的持续时间,如果持续时间小于1天,它以天为单位计算持续时间,返回0,但我不想显示0。在这种情况下,如果持续时间小于1天,我想最近显示 HTML 在执行这项任务时有几种原因 第一个是快速的,但由于绑定相对较多,性能非常差: <div> <span *ngIf="firstdate | myPipe : agent.lastUpdated"> {{firstdate | myPipe : agent.lastUpdate

我实现了一个管道,它获取两个值并查找它们之间的持续时间,如果持续时间小于1天,它以天为单位计算持续时间,返回0,但我不想显示0。在这种情况下,如果持续时间小于1天,我想最近显示

HTML


在执行这项任务时有几种原因

第一个是快速的,但由于绑定相对较多,性能非常差:

<div>
  <span *ngIf="firstdate | myPipe : agent.lastUpdated">
    {{firstdate | myPipe : agent.lastUpdated}} d ago
  </span>
  <span *ngIf="!(firstdate | myPipe : agent.lastUpdated)">
    recently
  </span>
</div>
因此,用法很简单:

{{firstdate | dayDiff : agent.lastUpdated | dayDiffDisplay}}

谢谢,你的两个答案都是有效的,但我有一个问题,我应该实施第一个建议吗?因为2管道比bindinghm需要更多的时间,实际上第二种方法应该工作得更快,我认为,因为这里只有两个绑定2管道,而且管道是纯的,所以如果值没有改变,那么angular不需要更新。在第一种情况下,每次使用ngif表达式中的管道进行更改检测时,将处理两个ngif,如果第一个正常,则将处理另外一个管道。但这些只是我的怀疑,如果你检查第一个更快,那么你可以使用它。
<div>
  <span *ngIf="firstdate | myPipe : agent.lastUpdated">
    {{firstdate | myPipe : agent.lastUpdated}} d ago
  </span>
  <span *ngIf="!(firstdate | myPipe : agent.lastUpdated)">
    recently
  </span>
</div>
@Pipe({
  name: 'dayDiff',
  pure: true
})
export class DayDiff implements PipeTransform {
  private millisecondsInDay = 24 * 3600 * 1000;
  transform(from: any , till: any): any {
     if(!from || !till){
         return from;
     }
     const fromDate = new Date(from);
     const tillDate = new Date(till);
     return Math.floor((firstDate - secondDate) / this.millisecondsInDay);
  }
}

...

@Pipe({
  name: 'dayDiffDisplay',
  pure: true
})
export class DayDiffDisplay implements PipeTransform {
  transform(diff: number): any {
     if(!diff){
         return 'recently';
     }
     return `${diff} d ago`;
  }
}

{{firstdate | dayDiff : agent.lastUpdated | dayDiffDisplay}}