3

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>
Soni Silalahi
  • 249
  • 2
  • 5
  • 15

1 Answers1

18

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">
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • Yes, the first block is for your .ts and the second block is for your .html – wentjun Feb 19 '19 at 07:44
  • 1
    @wentjun, you needn't use NgbDateConfig. if you use NgbDateConfig ALL your ngbDate will be affected. to use any properties in API https://ng-bootstrap.github.io/#/components/datepicker/api can be used in control, e.g. < ngb-datepicker #dp [minDate]="minDate" ...> – Eliseo Feb 19 '19 at 08:49
  • Oh yes that is right.. Ok I will update my answer accordingly – wentjun Feb 19 '19 at 08:53
  • yes. before you edited it. it makes wrong days each first week. but it works now. thanks a lot. you save my day :) – Soni Silalahi Feb 19 '19 at 09:54