user8944795
user8944795

Reputation:

How to disable previous date in ngbDatepicker in Angular 4?

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}" />

Upvotes: 4

Views: 10264

Answers (2)

wentjun
wentjun

Reputation: 42516

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

Upvotes: 6

KingDSL
KingDSL

Reputation: 119

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.

Upvotes: 7

Related Questions