Search code examples
angular6ng-bootstrapngb-datepicker

How to allow month navigation in ngbdatepicker while keeping the dates selection disabled?


Angular version: 6
Library: ngbbootstrap
Library reference links:
https://ng-bootstrap.github.io/#/components/datepicker/examples
https://ng-bootstrap.github.io/#/components/datepicker/api

Using the above library to display specific dates, I need to enable the month navigation of datepicker but disable selection(clicking) of dates.

Following is my code to render datepicker, where in <ng-template> is used for custom day view:

<ngb-datepicker #datepicker [(ngModel)]="model" (navigate)="date = $event.next" (select)="onDateSelect($event)"
            (ngModelChange)="onModelChange($event)" [dayTemplate]="templete" [disabled]="disabled" [firstDayOfWeek]="0"></ngb-datepicker>
        <ng-template #templete let-date="date">
            <span *ngIf="!showFixedDates" class="custom-day" [class.range]="isFrom(date) || isTo(date) || isInside(date) || isHovered(date)"
                [class.faded]="isHovered(date) || isInside(date) || (isContains(date) && showFixedDates)"
                [class.focused]="focused && showFixedDates" [class.hidden]="isPrevious(date) || isAfter6Months(date)"
                [class.previousRangeExtremes]="isPrevious(date) && ( isFrom(date) || isTo(date))" [class.previousRange]="isPrevious(date) && isInside(date)"
                (mouseenter)="hoveredDate = date" (mouseleave)="hoveredDate = null">
                {{ date.day }}
            </span>

            <span *ngIf="showFixedDates" class="custom-day" [class.focused]="focused" 
                [class.range]="isContains(date)" (mouseenter)="hoveredDate = date" (mouseleave)="hoveredDate = null">
                {{ date.day }}
            </span>
        </ng-template>

Some help on this will be great!


Solution

  • You can use the markDisabled function to mark specific dates as disabled. Set this on your ngb-datepicker as follows:

    <ngb-datepicker #datepicker 
        [(ngModel)]="model" 
        [markDisabled]="isDisabled"
        ...
    >
    </ngb-datepicker>
    

    Then define an isDisabled function that will return true (this has the effect of marking all dates as disabled):

     isDisabled = (date: NgbDate, current: {month: number}) => true;
    

    The month navigation controls will still be active, but no dates will be selectable. Please see this StackBlitz for a demo.