How to disable previous date in ngbDatepicker in Angular 4?

耗尽温柔 提交于 2019-12-06 07:34:21

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()
  };
}

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.

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