如何限制angular2-date-picker未来日期选择

时间:2019-02-13 06:32:09

标签: angular validation date datepicker

我不想允许用户在angular2-date-picker中选择将来的日期,我如何实现这种行为?我的代码如下。

<div class="col-md-6 col-lg-6 col-sm-12">
   <div>
     <label>From
        <angular2-date-picker
          [(ngModel)]="fromDate"
          [settings]="settings"
          (click)="customizeFromDatePicker()"
        ></angular2-date-picker
     ></label>
   </div>
    <div>
      <label
        >To
        <angular2-date-picker
          [(ngModel)]="toDate"
          [settings]="settings"
          (click)="customizeToDatePicker()"
        ></angular2-date-picker
      ></label>
    </div>
 </div>

2 个答案:

答案 0 :(得分:1)

您使用的angular2选择器有一个限制。

这是另一个最适合您的Angular 2日期选择器。

Here is link

这是实现步骤。

步骤1 :安装库:npm install angular2-datepicker

第2步:在AppModule中导入模块:

import {MyDatePickerModule} from 'mydatepicker';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    MyDatePickerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

第3步:app.component.html

<form [formGroup]="datepickerForm" novalidate>
    <my-date-picker name="mydate" 
            [options]="myDatePickerOptions"
            formControlName="startDate"
            (dateChanged)="onDateChanged($event)">
      </my-date-picker>
  <!-- other controls are here... -->
  <button (click)="showSelectedDate()">Submit</button>
</form>

步骤4 :app.component.ts

export class AppComponent {
  name = 'Angular 5';
  datepickerForm: FormGroup;
  selectedDate: any;
  myDatePickerOptions: any;

  constructor(public _formBuilder: FormBuilder) {
    this.datepickerForm = this._formBuilder.group({
      'startDate': [null, Validators.required]
    });
  }

  ngOnInit() {
    this.myDatePickerOptions = {
      dateFormat: 'dd-mm-yyyy',
      disableUntil : {year: 2016, month: 7, day: 22},
      disableSince :  {year: 2019, month: 4, day: 22}
    }
  }

  showSelectedDate() {
    let date: any = this.datepickerForm.controls['startDate'].value;
    this.selectedDate = date.formatted;
    console.log(this.selectedDate);
  }

  onDateChanged(event) {
    console.log(event);
  }
}

Here working solution on stackblitz

答案 1 :(得分:0)

您可以使用属性disableSince

在执行此操作之前,您可能需要先获取将来的日期:

get tomorrowDate(): Date {
   const todayDate = new Date();
   const tomorrowDate = new Date(todayDate.getTime() + 24 * 60 * 60 * 1000);

   return tomorrowDate;
}

然后,您可以插入disableSince属性以使其起作用:

this.myDatePickerOptions = {
   dateFormat: 'dd-mm-yyyy',
   disableSince: { year: this.tomorrowDate.getFullYear(), month: this.tomorrowDate.getMonth() + 1, day: this.tomorrowDate.getDate() }
}

Working Stackblitz Example

希望这会有所帮助!