How to disable previous date in ngbDatepicker in Angular 4?

半城伤御伤魂 提交于 2019-12-08 02:39:40

问题


I want to disable all the previous/past date in ngbDatepicker, I have used ngbDatepicker.
My HTML is:

<input required class="form-control" placeholder="dd-MM-YYYY" name="startDate" required ngbDatepicker #d="ngbDatepicker"
            [readonly]="true" [formControl]="formModel.controls.startDate" [ngClass]="{'has-error':!formModel.controls['startDate'].valid && formModel.controls['startDate'].touched}" />

回答1:


You could create an Implementation of NgbDatepickerConfig specifying when starts and ends your picker.

Here you have an example:

Html:

<div class="form-group">
  <div class="input-group">
    <input class="form-control" placeholder="yyyy-mm-dd" name="dp"[markDisabled]="isDisabled" ngbDatepicker #d="ngbDatepicker">
    <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button">
    </button>
  </div>
</div>

Component.ts

constructor(config: NgbDatepickerConfig) { 

    const currentDate = new Date();

    config.minDate = {year:currentDate.getFullYear(), month:currentDate.getMonth()+1, day: currentDate.getDate()};
    config.maxDate = {year: 2099, month: 12, day: 31};

    config.outsideDays = 'hidden';
  }

You can also disable specific dates using this feature, follow this link for more info, check: 'Global configuration of datepickers' section.




回答2:


Sorry for being late. I just came across this question, and the above answer that mutates the properties of NgbDatcConfig. That solution works fine, but it will affect all the other NgbDatepicker instances. The recommended way to do so would be to make use of the [minDate] input binding as stated on the API.

You can use it this way on your component.html,

 <input class="form-control" ngbDatepicker [minDate]="minDate" (click)="datePicker.toggle()" #datePicker="ngbDatepicker"" placeholder="yyyy-mm-dd">

And on your component.ts, you can define minDate in this manner:

minDate = undefined;
.
. 
constructor(private config: NgbDatepickerConfig) {
  const current = new Date();
  this.minDate = {
    year: current.getFullYear(),
    month: current.getMonth() + 1,
    day: current.getDate()
  };
}


来源:https://stackoverflow.com/questions/49559718/how-to-disable-previous-date-in-ngbdatepicker-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!