按日期过滤角度4中的列表数据

时间:2018-11-26 22:22:04

标签: angular angular-pipe

我有一个包含用户生日的列表。我想显示生日从现在开始的用户列表。

我想显示生日从今天起一周内的用户列表。

我的列表就像

`<nb-list-item *ngFor="let yuvak of yuvaklist | slice:startDate:endDate ">
      {{yuvak.dateofbirth}}
      {{yuvak.firstname}} + + {{yuvak.lastname}}
  </nb-list-item>`

2 个答案:

答案 0 :(得分:0)

下面的简单示例:

let weekSec = 7 * 24 * 60 * 60 * 1000;
let today = new Date();
let birthday = new Date('1995-11-22');
birthday.setFullYear(today.getFullYear());
if (birthday.getTime() < today.getTime() && birthday.getTime() + weekSec > today.getTime()) {
  console.log('Happy birthday');
} else {
  console.log('...');
}

答案 1 :(得分:0)

同意@incNick代码,但这应该包装在Pipe中。您可以这样创建Angular管道过滤器。

从'@ angular / core'导入{Pipe,PipeTransform};

@Pipe({
    name: 'birthdayFilter',
    pure: false
})

export class FilterPipe implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => this.isBirthdayInaWeek(item.birthday));
    }

    isBirthdayInaWeek(birthday){
        let weekSec = 7 * 24 * 60 * 60 * 1000;
        let today = new Date();
        let birthday = new Date(birthday);
        birthday.setFullYear(today.getFullYear());
        if (birthday.getTime() < today.getTime() && birthday.getTime() + weekSec > today.getTime()) {
            return true;
        } else {
           return false;
        }
    }
} 

模板:

<nb-list-item *ngFor="let yuvak of yuvaklist | birthdayFilter ">
      {{yuvak.dateofbirth}}
      {{yuvak.firstname}} + + {{yuvak.lastname}}
  </nb-list-item>