Disable ngbDatepicker input

Hadi Rasouli picture Hadi Rasouli · Sep 28, 2017 · Viewed 11.1k times · Source

Im using ngbDatepicker and ng2-datepicker-jalali. I use ngbDatepicker directive like below:

   <div class="input-group" dir="ltr">
      <input class="form-control" 
          placeholder="yyyy/m/d" 
          name="dp" 
          [(ngModel)]="registerDate" 
          ngbDatepicker 
          [firstDayOfWeek] = "6"
          [disabled]="disabled"
          #d="ngbDatepicker" >
          <button class="input-group-addon" (click)="d.toggle()" type="button">
              <i class="fa fa-calendar"></i>
          </button>
    </div>

I'm trying to disable input to force select date from datepicker. [disabled]="disabled" attr disables whole datepicker.

Answer

Ian A picture Ian A · Oct 1, 2017

You could use:

[readonly]="true"

on the <input> which has the effect of turning the input into a readonly input meaning the user will be forced to select using the date picker:

<div class="input-group" dir="ltr">
  <input class="form-control" 
    placeholder="yyyy/m/d" 
    name="dp" 
    [(ngModel)]="model" 
    ngbDatepicker 
    [firstDayOfWeek] = "6"
    [readonly]="true"
    #d="ngbDatepicker" >
    <button class="input-group-addon" (click)="d.toggle()" type="button">
      <i class="fa fa-calendar"></i>
    </button>
</div>

The only problem is there is no way I can find to clear the datepicker without deleting the text in the input, so you may need to implement a button to clear the date if required:

<button (click)="clear()" type="button">Clear</button>

public clear(): void {
  this.model = undefined;
}

Here's a demo: http://plnkr.co/edit/gYneFD?p=preview