首页 > 解决方案 > Angular 8:隐藏过去事件的管道不起作用

问题描述

bookingEnd我在模板中创建了一个复选框,根据我的 JSON 数据隐藏所有早于今天发生的元素。recent-filter.pipe.ts管道应该过滤所有过去的事件。

对于我的问题,我error TS2365: Operator '>' cannot be applied to types 'number' and 'Date'.提前在管道中获得了一个,并且没有数据显示在我的模板上。整个场景在纯 JavaScript 中工作,所以我认为这bookingEnd绝对是一个日期对象。

你能帮我为什么应用管道过滤器后没有数据吗?

JSON数据:

{
  bookingStart: "2019-10-27T23:00:00.000Z",
  bookingEnd: "2019-12-29T23:00:00.000Z",
  city: "Manhattan",
  confirmed: false,
  country: "UK"
}

最近-filter.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'recentFilter'
})
export class RecentFilterPipe implements PipeTransform {
  transform(list: any[], checked: boolean) {
    if (checked) {
      const futureDates = list.filter(x => {
        return Date.parse(x.bookingEnd) > new Date();
      });
      return futureDates;
    } else {
      return list;
    }
  }
}

预订表.component.html:

<tr
  *ngFor="
    let item of bookings
    | recentFilter: checked
  ">
      ...
</tr>

标签: javascriptangulardatepipe

解决方案


您得到的错误已经告诉您不要使用 > 来比较日期
要比较它们,请使用 .getTime() 方法

new Date(x.bookingEnd).getTime() > new Date().getTime()

推荐阅读