With Angular Material's mat-date-range-input, how do you build a pick-up and return range that blocks unavailable dates, and what does the filter miss?
answer
- two inputs, one range panel
- start and end marker directives
- the range input links the panel
- filter input name differs from single picker
- endpoints checked, days between not
basics
~20 sWrap matStartDate and matEndDate inputs in mat-date-range-input, link it to a mat-date-range-picker with [rangePicker], and block days with [dateFilter], [min] and [max]. The filter only validates the two endpoints, so a range can still span a blocked day.
solid answer
~40 sA range is one `mat-date-range-input` holding two inputs, `matStartDate` and `matEndDate`, plus a `mat-date-range-picker` linked through `[rangePicker]`; with reactive forms you bind a `FormGroup` to the range input and `formControlName` to each part. Blocking happens on the range input: `[min]` and `[max]` bound the calendar and stop navigation past them, and `[dateFilter]` (on a single datepicker input the same job is `matDatepickerFilter`) disables individual days. Violations surface as `matDatepickerMin`, `matDatepickerMax` or `matDatepickerFilter` on the offending endpoint control, and an end before the start gives `matEndDateInvalid` and `matStartDateInvalid`. The gap: the filter is asked only about the start and end values, so 23 to 27 October passes even when the 25th is blocked. Close it with a group validator that walks the days, or a custom `MatDateRangeSelectionStrategy` provided through `MAT_DATE_RANGE_SELECTION_STRATEGY`.
code
ts · 20 linesimport {AbstractControl, ValidationErrors, ValidatorFn} from '@angular/forms';
import {DateTime} from 'luxon';
export function noBlockedDays(blocked: Set<string>): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const start: DateTime | null = group.get('pickUp')?.value ?? null;
const end: DateTime | null = group.get('returnDate')?.value ?? null;
if (!start || !end) {
return null;
}
for (let day = start.startOf('day'); day <= end; day = day.plus({days: 1})) {
if (blocked.has(day.toISODate()!)) {
return {spansBlockedDate: {day: day.toISODate()}};
}
}
return null;
};
}
// new FormGroup({...}, {validators: noBlockedDays(blockedDays)})go deeper
Recall the pieces: mat-date-range-input with matStartDate and matEndDate inside, a mat-date-range-picker, and the rangePicker binding.
Explain min, max and dateFilter on the range input, the error keys each endpoint control can carry, and how a FormGroup maps onto the two inputs.
Spot that the filter validates only the endpoints and close the gap with a group validator, a selection strategy where the interaction must change, and a server re-check.
Decide where availability truth lives: client filters are a convenience for a stale snapshot, so the booking contract and its error path belong to the server.
## Anatomy of a range Angular Material builds date ranges from four pieces: - **`mat-date-range-input`**: the container. Its value is a `DateRange<D>` with `start` and `end`, and it acts as the form-field control for the pair. - **`input[matStartDate]`** and **`input[matEndDate]`**: the two text inputs. Each one is a full value accessor and validator, so each gets its own form control. - **`mat-date-range-picker`**: the calendar panel. It works like `mat-datepicker`, but a selection takes two clicks. - **`[rangePicker]`**: the range input's binding that connects it to the panel, while the toggle still uses `[for]`. Other inputs of the range container are `separator` (default `–`) and `comparisonStart` / `comparisonEnd`, which draw a second, read-only range for comparison. ## Wiring it with reactive forms ```ts readonly rental = new FormGroup({ pickUp: new FormControl<DateTime | null>(null), returnDate: new FormControl<DateTime | null>(null), }); ``` ```html <mat-date-range-input [formGroup]="rental" [rangePicker]="rentalPicker" [min]="today" [dateFilter]="isBookable"> <input matStartDate formControlName="pickUp"> <input matEndDate formControlName="returnDate"> </mat-date-range-input> <mat-datepicker-toggle [for]="rentalPicker" /> <mat-date-range-picker #rentalPicker /> ``` The value type is whatever the provided `DateAdapter` uses; here the Luxon adapter, so `DateTime`. ## Blocking dates: min, max and the filter | Mechanism | Where it goes | What it does in the calendar | Validation error | |---|---|---|---| | `[min]` | range input (or single input) | disables earlier days and stops navigation before that month | `matDatepickerMin` | | `[max]` | range input (or single input) | disables later days and stops navigation past that month | `matDatepickerMax` | | `[dateFilter]` | range input | disables each day the function rejects; navigation stays free | `matDatepickerFilter` | | `matDatepickerFilter` | single `matDatepicker` input | same job for a single date | `matDatepickerFilter` | The filter is a `DateFilterFn<D>`, a function `(date: D | null) => boolean` where `true` means selectable. Keep it cheap, because the calendar calls it for every visible cell. The input names differ between the two: `mat-date-range-input` has no `matDatepickerFilter` input, so binding `[matDatepickerFilter]` there is a template compile error rather than a working filter. ## Errors on the endpoints 1. A typed day the filter rejects puts `matDatepickerFilter` on that endpoint's control. 2. A start after the end puts `matStartDateInvalid` on the start control and `matEndDateInvalid` on the end control. 3. Unparsable text puts `matDatepickerParse` on the control that holds it. ## What the filter does not check The default range strategy only records the first click as `start` and a later-or-equal second click as `end`. The filter validator then checks the start value and the end value. **Nothing asks about the days in between.** A customer can choose 23 October to 27 October while the 25th, the day the car is serviced, is blocked; both endpoints pass and the form is valid. ## Closing the gap - **Group validator**: attach a validator to the `FormGroup` that walks from start to end with the adapter (or Luxon's own arithmetic) and returns an error such as `{spansBlockedDate: true}`. This also protects typed input and programmatic values. - **Selection strategy**: implement `MatDateRangeSelectionStrategy<D>`, whose `selectionFinished` and `createPreview` methods decide the range from each click and hover, and provide it with `MAT_DATE_RANGE_SELECTION_STRATEGY`. It can refuse or trim a selection that crosses a blocked day, but it only governs calendar clicks, so keep the validator as the real guard. - **Server check**: availability changes between page load and submit, so the backend must re-check the booking anyway.
- Why does the calendar still let the customer page forward past a fully booked month when you use only the filter?`min` and `max` both disable days and stop navigation beyond their month, but `dateFilter` only disables the cells it rejects. A filter that rejects every day after a point still leaves the next-month button working. Use `max` for a hard horizon and the filter for scattered blocked days.
- When is a custom MatDateRangeSelectionStrategy the better tool than a validator?When the calendar interaction itself should change: forcing a fixed length, such as a weekend package from Friday to Monday, or previewing and snapping the range as the user hovers. `selectionFinished` and `createPreview` decide the range per click and hover. It does not see typed text, so pair it with a validator.
- matDatepickerFilter on mat-date-range-input disables days in the range calendar.
- A date filter rejects any range that contains a blocked day.
- The filter stops navigation past the last allowed month, just like max.
- One form control holds the whole range, so matStartDate and matEndDate need no controls.
- An end date before the start date simply swaps the two values.