Search code examples
angularangular-pipe

Filter list data by dates in angular 4


I have one list that contains birthdate of user. I want to display list of users whose birthday is one from now.

i want to display list of users whose birthdays are in one week from today.

My list is like

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

Solution

  • Agree with @incNick Code, But that should we wrapped inside Pipe. You can create Angular pipe filter like this.

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

    @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;
            }
        }
    } 
    

    Template:

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