Skip to content

limit date range

Keke edited this page Dec 10, 2020 · 4 revisions

Limit date range to begin date + 7 days.

<input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" [defaultMonth]="defMonth" 
    #dp="angular-mydatepicker" (rangeDateSelection)="onRangeDateSelection($event)"/>
import {AngularMyDatePickerDirective, IAngularMyDpOptions, IMyRangeDateSelection} from 'angular-mydatepicker';

export class MyApp {
  @ViewChild('dp') ngxdp: AngularMyDatePickerDirective;

  myDatePickerOptions: IAngularMyDpOptions = {
      dateRange: true
      // other options here...
  }

  defMonth: IMyDefaultMonth = {
    defMonth: '',
    overrideSelection: false 
  };

  constructor() {}

  onRangeDateSelection(event: IMyRangeDateSelection): void {
    console.log('onRangeDateSelection(): event: ', event);

    let {isBegin, date, jsDate} = event;

    let options: IAngularMyDpOptions = this.getCopyOfOptions();

    if(isBegin) {
        // start date selection - set disable since (selected date + 7 days)
        this.ngxdp.writeValue({
          isRange: true, 
          singleDate: null, 
          dateRange: {
            beginDate: {year: 0, month: 0, day: 0},
            endDate: {year: 0, month: 0, day: 0}
          }
        });

        this.ngxdp.setHostValue('');

        let d = new Date(jsDate.getTime());
        d.setDate(d.getDate() + 7);
        
        options.disableSince = {year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate()};
        this.myDatePickerOptions = options;

        this.defMonth = {
          defMonth: date.month + '.' + date.year,
          overrideSelection: true
        };
    }
    else {
        // end date selection - remove disableSince option
        options.disableSince = {year: 0, month: 0, day: 0};
        this.myDatePickerOptions = options;

        let d: Date = new Date();

        let month: any = d.getMonth() + 1;
        if (month < 10) {
          month = '0' + month;
        }

        this.defMonth = {
          defMonth: month + '.' + d.getFullYear(),
          overrideSelection: false
        };
    }
  }

  // get copy of options
  getCopyOfOptions(): IAngularMyDpOptions {
      return JSON.parse(JSON.stringify(this.myDatePickerOptions));
  }
}