ngIf条件获得多余价值

时间:2018-07-18 13:44:10

标签: angular

我有一个div,它显示我要隐藏的日期,只显示最近的日期

    <div class="users" *ngFor="let user of users; let i = index" [attr.data-index]="i">
            <div *ngIf="user.recipient === selectedUser._id && showUser(user)">
                <div class="user-date">
                  {{ user.date | date:'EEEE'}} {{user.date | date:'d'}} {{ user.date | date:'MMMM'}} {{ user.date |
                  date:'yyyy'}}
              </div>
    <div>

此刻,我正在这样显示它:

["Mon Jul 16 2018 11:40:28 GMT+0200 (CEST)",
 "Fri Jul 13 2018 09:33:46 GMT+0200 (CEST)",
 "Fri Jul 13 2018 09:21:36 GMT+0200 (CEST)",
 "Fri Jul 13 2018 09:03:42 GMT+0200 (CEST)",
 "Fri Jul 13 2018 09:01:05 GMT+0200 (CEST)",
 "Fri Jul 13 2018 08:53:23 GMT+0200 (CEST)",
 "Fri Jul 13 2018 08:52:33 GMT+0200 (CEST)",
 "Thu Jul 12 2018 13:41:59 GMT+0200 (CEST)",
 "Thu Jul 12 2018 13:41:49 GMT+0200 (CEST)",
 "Thu Jul 12 2018 13:41:42 GMT+0200 (CEST)"]

我想要实现的是做一个ngFor,所以我只能这样得到:

   [ "Thu Jul 12 2018 13:41:59 GMT+0200 (CEST)"
    "Mon Jul 16 2018 11:40:28 GMT+0200 (CEST)",
     "Fri Jul 13 2018 09:33:46 GMT+0200 (CEST)"]

这将显示最近的日期

一次闪电战:https://stackblitz.com/edit/stacktest

2 个答案:

答案 0 :(得分:0)

完成此操作的最佳方法是在组件中执行过滤。

//组件

public getMostRecentDatesPerDay() {
  const results = {};
  this.users.forEach(user => {
    const key = (new Date(user.date.getFullYear(), user.date.getMonth(), user.date.getDate())).toString();
    const existingDate = results[key];
    if (existingDate === undefined || existingDate < user.date) {
      results[key] = user.date;
    }
  });
  return Object.values(results);
}

// HTML

<div class="users" *ngFor="let user of getMostRecentDatesPerDay(); let i = index" [attr.data-index]="i">
  <div *ngIf="user.recipient === selectedUser._id && showUser(user)">
    <div class="user-date">
      {{ user.date | date:'EEEE'}} {{user.date | date:'d'}} {{ user.date | date:'MMMM'}} {{ user.date | date:'yyyy'}}
    </div>
  </div>
<div>

说明/注释:

该函数通过将唯一的key值确定为没有时间成分的日期来工作。然后,它会比较现有值,以便将唯一值设置为当天的最新值。

注意:使用Moment.js会容易得多,如果您要进行大量的日期逻辑操作,我强烈建议您查看此库。

警告:如果用户阵列很大,则可能会影响性能。当绑定到HTML中的函数时,每次更改检测通过都会重新评估该函数。如果存在问题,则应在安装时或users数组更改时运行该函数,然后将结果存储到component字段中。


没有组件?没问题!

Reference Tutorial

// Custom Pipe

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

@Pipe({name: 'uniqueByDate'})
export class UniqueByDate implements PipeTransform {
  transform(values: { date: Date }[]): string {
    const results = {};
    values.forEach(value => {
      const key = (new Date(value.date.getFullYear(), value.date.getMonth(), value.date.getDate())).toString();
      const existingDate = results[key];
      if (existingDate === undefined || existingDate < value.date) {
        results[key] = user.date;
      }
    });
    return Object.values(results);
  }
}

// HTML

<div class="users" *ngFor="let user of users | uniqueByDate; let i = index" [attr.data-index]="i">
  <div *ngIf="user.recipient === selectedUser._id && showUser(user)">
    <div class="user-date">
      {{ user.date | date:'EEEE'}} {{user.date | date:'d'}} {{ user.date | date:'MMMM'}} {{ user.date | date:'yyyy'}}
    </div>
  </div>
<div>

先前的说明/注释仍然适用

答案 1 :(得分:0)

您可以使用Pipe来做到这一点:

示例01:((如果您仅在{kbd> DEMO 中使用dates: string[]

按如下所示实施Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
  name: 'dateFilter'
})
export class DateFilterPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    let diplayDates: any[] = []
    let datePipe = new DatePipe('en-US');
    let filteredDateTimes = [];
    let filteredDates = [];

    value.forEach((date) => {    
      diplayDates.push(new Date(date));
    });

    let sortDates = diplayDates.sort((a: any, b: any) => {
      let date1: any = new Date(b);
      let date2: any = new Date(a);
      return date1 - date2;
    });

    sortDates.forEach((date) => {
      let day = datePipe.transform(date, 'yyyy-MM-dd');
      let index = filteredDates.indexOf(day);
      if (index === -1) {
        filteredDates.push(day);
        filteredDateTimes.push(date);
      }
    });

    return filteredDateTimes;
  }

}

像下面这样在您的HTML中应用它:

<div *ngFor="let date of dates | dateFilter ; let i = index" [attr.data-index]="i">
  {{date | date:'EEEE'}} {{date | date:'d'}}  {{ date | date:'MMMM'}} {{ date |date:'yyyy'}}
</div>

WORKING DEMO


示例02:((如果您仅使用users数组,如您的问题中那样)

像这样更改您的Pipe

 transform(value: any, args?: any): any {
    let diplayDates: any[] = []
    let datePipe = new DatePipe('en-US');
    let filteredDateTimes = [];
    let filteredDates = [];

    value.forEach((user) => {
      user.date = new Date(user.date)
      diplayDates.push(user);
    });

    let sortDates = diplayDates.sort((a: any, b: any) => {
      let date1: any = new Date(b.date);
      let date2: any = new Date(a.date);
      return date1 - date2;
    });


    sortDates.forEach((user) => {
      let day = datePipe.transform(user.date, 'yyyy-MM-dd');
      let index = filteredDates.indexOf(day);
      if (index === -1) {
        filteredDates.push(day);
        filteredDateTimes.push(user);
      }
    });

    return filteredDateTimes;
  }

并像这样在HTML中使用Pipe

<div *ngFor="let user of users | dateFilter ; let i = index" [attr.data-index]="i">
  {{user.date | date:'EEEE'}} {{user.date | date:'d'}}  {{ user.date | date:'MMMM'}} {{ user.date |date:'yyyy'}}
</div>

WORKING DEMO

希望这对您有帮助!