angularngb-datepicker

How to disable past dates using ngbDatePicker Plugin on Angular


i'm using ngbDatePicker plugin in Angular, i have tried all javascript code in html but nothing works. Pastdate still enable to selected.

here's the html code

<div class="col-xs-6">
  <label><i class="far fa-calendar-alt"></i> Start <span class="text-danger">*</span></label>
   <input id="startTrip1" data-provide="datepicker" ngbDatepicker #d="ngbDatepicker" type="text" class="form-control form-flat" [(ngModel)]="ad.start_date" (dateSelect)="onDateSelect($event, ad)" (blur)="validateInput()" (click)="d.toggle()" [ngModelOptions]="{standalone: true}" [disabled]="form.controls.tripduration.hasError('required')" >
      <div class="text-danger" *ngIf="(ad.start_date == '' || ad.start_date == undefined) && ngForm.submitted">
      * This field is required
     </div>
</div>

Solution

  • I have encountered this before, this is how I solved it. Do remember to import NgbDatepickerConfig into your component.ts.

    import { NgbDatepickerConfig, . . . } from '@ng-bootstrap/ng-bootstrap';
    .
    .
    constructor(private config: NgbDatepickerConfig) {
      const current = new Date();
      config.minDate = { year: current.getFullYear(), month: 
      current.getMonth() + 1, day: current.getDate() };
        //config.maxDate = { year: 2099, month: 12, day: 31 };
      config.outsideDays = 'hidden';
    }
    

    And on the component.html,

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

    formControlName only applies if you are using reactive forms. If you are not, feel free to ignore it.

    [EDIT] As @Eliseo pointed out on the comments, it is sufficient to use minDate, such that it will not affect all other instances of the Datepicker. On your component.ts,

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

    And on your component.html, use the [minDate] input bindings

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