How to disable all days except the 'Mondays' in ngb-datepicker?

810 Views Asked by At

I want to disable all days except the 'Mondays' or 'Fridays' etc... in ngb-datepicker?

Template:

<input [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker" [markDisabled]="isDisabled"/>

Component:

this.isDisabled = (date: NgbDate) =>(date.day) !== 1;
2

There are 2 best solutions below

0
Alex Hodson On

I realise this is almost a year old, but with that being said, this is how I resolved the same issue in my code.

Inside the component file I specified an object containing the days to be restricted (you can specify to restrict every day as a whole, for example all tuesdays, and you can specify to restrict specific dates).

dateRestrictions = {
  days: [2, 3, 4, 6, 7], // Disables day tuesday, wednesday, thursday, saturday, sunday)
  specificDates: [ // Disables the following dates in general
    { year: 2022, month: 7, day: 12 },
    { year: 2022, month: 7, day: 24 },
    { year: 2022, month: 9, day: 5 }
  ]
}

Inside the constructor, provide an instance to the NgbCalendar and define a method which will check the date provided by the date picker and determine if it should be disabled according to your rules. This method will need to return a boolean (represents whether the date should be restricted).

constructor(private calendar: NgbCalendar) {
        const { specificDatesToRestrict, daysToRestrict } = this.dateRestrictions!
    this.isDisabled = (date: NgbDateStruct) => {
            return !!specificDatesToRestrict?.find(x =>{
                const restrictionDate = new NgbDate(x.year, x.month, x.day)
    
                return restrictionDate.equals(date) // If the date matches a specific date
            }) || daysToRestrict?.includes(this.calendar.getWeekday(new NgbDate(date.year,date.month,date.day))) // If the day number matches in the restriction rules
        }
}

Then, simply bind that method to the markDisabled property of your input element.

<input 
    class="form-control text-grey"
    placeholder="Please select a date"
    [readonly]="true"
    ngbDatepicker
    #d="ngbDatepicker"
    [markDisabled]="isDisabled"
>

This will work even if you pass a minimum and maximum date to your date picker.

0
Lautaro Lopez Ruiz On

I think you need to inject NgbCalendar service in your component contructor

import {NgbCalendar} from '@ng-bootstrap/ng-bootstrap';

constructor(private ngbCalendar: NgbCalendar) { }

and then make the function to mark as disabled days

public isDayDisabled = (date: NgbDate) => 
   this.ngbCalendar.getWeekday(date) !== 1;

finally call the function in markDisabled