根据与当前时间相比的时间戳过滤Angular 2中的字段

时间:2016-12-02 14:20:52

标签: angular angular-template

我正在构建一个显示对象列表的应用程序。每个对象都有一个archived_until属性,可以保存值 null 或没有时区的时间戳(例如: 2016-11-26 08:00:00.561139 )。

我正在尝试显示所有这些对象的列表,并为用户提供切换名为Show archived objects的按钮的可能性。我想知道将Angular 2中的时间戳与当前日期进行比较的最佳方法是什么?我可以在模板中使用它,还是应该在组件中编写函数?

这是我到目前为止所尝试的,它不会返回任何错误,但也不会按预期过滤(它什么都不显示)。我添加了一个切换show_archived_notes

的值的按钮
<tr *ngFor="let notification of notifications">
    <ng-container 
     *ngIf=(!show_archived_notes && !notification.archived_until) || 
     notification.archived_until > currentDate>
        <td>Some attribute</td><td>Another attribute</td>...
    </ng-container>
</tr>

我在我的组件中初始化currentDate的位置如下:

current_date = new Date();

1 个答案:

答案 0 :(得分:0)

您可以使用更简单的方法,编写管道来过滤存档并添加活动参数:

<tr *ngFor="let notification of notifications | archivePipe:show_archived_notes">

管道将获取和数组,如果active为false,则按原样返回数组,如果不是,则按逻辑过滤。

@Pipe({
    name: 'archivePipe'
})
export class ArchivePipe implements PipeTransform {
  transform(notes: Array<Notes>, active: boolean): Array<Notes> {
      if(active){
          return notes.filter(<your archive filter logic>);
      } else {
          return notes;
      }
  }
}