Let's create a custom date picker component in Angular!
Here are all prerequisites:
Functionality wise:
Needs to support both picking a single date, as well as being able to select a date range, like this <gsd-datepicker [rangeMode]="true">
In single date mode, the calendar will close after selecting a date. In date range mode, the calendar stays open until the user confirms the date range with the save button
It should support min and max dates - so a user should not be able to select anything before the min date, and nothing past the max date <gsd-datepicker [minDate]="minDate" [maxDate]="maxDate">
It should also work if only minDate or maxDate is used
There should be a reset button which resets the selection back to the previous one
There should be a save button as well
It needs to support ReactiveForms, NgModel as well as work standalone
Coding wise:
Don't use the old *ngIf="showCalendar" syntax, instead use the new @if(showCalendar) {}
Don't use the old @Input() rangeMode: boolean = false, instead use the newer public rangeMode = input(false), and keep in mind this turns it into a signal.
Same goes for @Output, use public xxx = output() instead..
Make sure to set scope properly on everything, so public/protected/private.
The selector of the component should be "gsd-datepicker"
The name of the component should be DatepickerComponent
UX / UI wise:
In the input field, dates should be formatted as dd-mm-yyyy
Within the input field there should be a calendar on the left
Within the input field there should be a downward facing chevron on the right.
When the input field is clicked, the datepicker should open below. The chevron icon should change to a upward facing chevron.
When the datepicker is closed, the chevron should face down again.
Regarding the actual datepicker:
There needs to be a left sidebar which contains preset time range buttons in a vertical list: Today, Yesterday, Last week, Last 7 days, This month, Last 30 days, Custom Range
Custom range gets automatically selected when a user starts creating their own custom range in the calendar. Or if they click custom range, it should clear the selection
On the right is the calendar view:
It should display < {Month} {Year} > . Clicking on {Month} or {Year} should show a dropdown, which when clicked, allows the user to select the month / year from a list.
The navigation arrows should only be enabled if the previous/next month is available (based on minDate and maxDate)
The values in the Month and Year dropdown should also be dynamic and based on minDate / maxDate
It should use a Standard 7-column layout (Mo, Tu, We, Th, Fr, Sa, Su) with 6 rows.
Dates that are either not in this month or in the weekend should be light gray text color, otherwise black.
The current day should be a blue text color
Both selected dates should be prominently highlighted
Additionally a light blue selection should cover the selected period. This effect should show on hover, so while hovering over dates it should be visible what the date range is
In the footer of the modal are three buttons:
Aligned to the left is a Reset button
Aligned to the right is a Cancel and a Save button
import {
Component,
OnInit,
signal,
input,
output,
effect,
ChangeDetectionStrategy,
computed,
ElementRef,
HostListener,
inject,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import {
ControlValueAccessor,
NG_VALUE_ACCESSOR,
ReactiveFormsModule,
FormsModule,
} from '@angular/forms';
import {
addDays,
addMonths,
endOfDay,
formatDate,
getDaysInMonth,
getStartOfWeek,
isSameDay,
parseDate,
startOfDay,
CalendarDay,
} from './date-utils';
@Component({
selector: 'gsd-datepicker',
standalone: true,
imports: [CommonModule, ReactiveFormsModule, FormsModule],
templateUrl: './datepicker.component.html',
styleUrl: './datepicker.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: DatepickerComponent,
multi: true,
},
],
})
export class DatepickerComponent implements OnInit, ControlValueAccessor {
// --- Inputs & Outputs (using modern signal-based APIs) ---
public rangeMode = input<boolean>(false);
public minDate = input<Date | null>(null);
public maxDate = input<Date | null>(null);
// No specific output needed as we use ControlValueAccessor
// However, for standalone usage or if consumer needs an explicit event
// public dateSelected = output<Date | [Date | null, Date | null]>();
// --- Internal State Signals ---
public showCalendar = signal<boolean>(false);
public currentMonth = signal<number>(new Date().getMonth());
public currentYear = signal<number>(new Date().getFullYear());
// Store selected dates. For single mode, only _selectedStartDate is used.
private _selectedStartDate = signal<Date | null>(null);
private _selectedEndDate = signal<Date | null>(null);
private _hoverDate = signal<Date | null>(null); // Used for range hover preview
// Store the value that was passed via writeValue or the last saved value
// This is used for the Reset functionality.
private _previousValue: string | [string, string] | null = null;
// CVA related
private _onChange: (value: any) => void = () => {};
private _onTouched: () => void = () => {};
private _isDisabled = signal<boolean>(false); // Tracks disabled state from form control
// --- Computed Signals for UI Logic ---
public displayValue = computed<string>(() => {
if (this.rangeMode()) {
const start = this._selectedStartDate();
const end = this._selectedEndDate();
if (start && end) {
return `${formatDate(start)} - ${formatDate(end)}`;
} else if (start) {
return `${formatDate(start)} - (Select End Date)`;
}
return '';
} else {
return formatDate(this._selectedStartDate());
}
});
public currentMonthName = computed<string>(() => {
return new Date(
this.currentYear(),
this.currentMonth(),
1
).toLocaleString('default', { month: 'long' });
});
public calendarDays = computed<CalendarDay[][]>(() => {
const year = this.currentYear();
const month = this.currentMonth();
const today = startOfDay(new Date());
// Get the first day of the month
const firstDayOfMonth = new Date(year, month, 1);
// Get the Monday of the week containing the first day of the month
const startOfCalendar = getStartOfWeek(firstDayOfMonth, 1); // 1 for Monday
const days: CalendarDay[] = [];
for (let i = 0; i < 42; i++) {
// 6 weeks * 7 days
const date = addDays(startOfCalendar, i);
const day: CalendarDay = {
date: date,
isCurrentMonth: date.getMonth() === month,
isWeekend: date.getDay() === 0 || date.getDay() === 6, // 0: Sunday, 6: Saturday
isToday: isSameDay(date, today),
isDisabled: this._isDateDisabled(date),
isSelectedStart: isSameDay(date, this._selectedStartDate()),
isSelectedEnd: isSameDay(date, this._selectedEndDate()),
isInSelectedRange: this._isDateInSelectedRange(date),
isInHoverRange: this._isDateInHoverRange(date),
};
days.push(day);
}
// Convert flat array to 2D array (weeks)
const weeks: CalendarDay[][] = [];
for (let i = 0; i < days.length; i += 7) {
weeks.push(days.slice(i, i + 7));
}
return weeks;
});
public isPrevMonthDisabled = computed<boolean>(() => {
if (!this.minDate()) return false;
const firstDayOfCurrentMonth = new Date(
this.currentYear(),
this.currentMonth(),
1
);
const prevMonth = addMonths(firstDayOfCurrentMonth, -1);
return prevMonth < startOfDay(this.minDate()!);
});
public isNextMonthDisabled = computed<boolean>(() => {
if (!this.maxDate()) return false;
const lastDayOfCurrentMonth = endOfDay(
new Date(this.currentYear(), this.currentMonth() + 1, 0)
); // Last day of current month
const nextMonth = addMonths(lastDayOfCurrentMonth, 1);
return nextMonth > endOfDay(this.maxDate()!);
});
public availableMonths = computed<
{ value: number; name: string; disabled: boolean }[]
>(() => {
const months = [];
const minYear = this.minDate()?.getFullYear() ?? -Infinity;
const maxYear = this.maxDate()?.getFullYear() ?? Infinity;
const minMonth = this.minDate()?.getMonth() ?? 0; // 0 for Jan
const maxMonth = this.maxDate()?.getMonth() ?? 11; // 11 for Dec
for (let i = 0; i < 12; i++) {
const monthDate = new Date(this.currentYear(), i, 1);
let isDisabled = false;
// Disable months outside min/max year range
if (this.currentYear() < minYear || this.currentYear() > maxYear) {
isDisabled = true;
}
// If current year is minYear, disable months before minMonth
else if (this.currentYear() === minYear && i < minMonth) {
isDisabled = true;
}
// If current year is maxYear, disable months after maxMonth
else if (this.currentYear() === maxYear && i > maxMonth) {
isDisabled = true;
}
months.push({
value: i,
name: monthDate.toLocaleString('default', { month: 'long' }),
disabled: isDisabled,
});
}
return months;
});
public availableYears = computed<
{ value: number; disabled: boolean }[]
>(() => {
const years = [];
const currentYear = new Date().getFullYear();
const minYear = this.minDate()?.getFullYear() ?? currentYear - 100;
const maxYear = this.maxDate()?.getFullYear() ?? currentYear + 100;
for (let i = minYear; i <= maxYear; i++) {
years.push({ value: i, disabled: false }); // Years in range are always enabled
}
return years;
});
// --- Month/Year Picker State ---
public showMonthPicker = signal<boolean>(false);
public showYearPicker = signal<boolean>(false);
// --- Preset Ranges State ---
public presetRanges = computed(() => [
{ label: 'Today', handler: () => this.selectToday() },
{ label: 'Yesterday', handler: () => this.selectYesterday() },
{ label: 'Last 7 Days', handler: () => this.selectLast7Days() },
{ label: 'Last 30 Days', handler: () => this.selectLast30Days() },
{ label: 'This Month', handler: () => this.selectThisMonth() },
{ label: 'Last Month', handler: () => this.selectLastMonth() },
{ label: 'Custom Range', handler: () => this.selectCustomRange(), isCustom: true },
]);
public selectedPreset = signal<string | null>(null);
private elementRef = inject(ElementRef); // Used for click outside logic
constructor() {
// Effect to update current month/year when minDate/maxDate or selected dates change,
// ensuring the calendar view shows a relevant month.
effect(() => {
const min = this.minDate();
const max = this.maxDate();
const start = this._selectedStartDate();
if (start) {
this.currentMonth.set(start.getMonth());
this.currentYear.set(start.getFullYear());
} else if (min && min.getFullYear() > this.currentYear()) {
this.currentMonth.set(min.getMonth());
this.currentYear.set(min.getFullYear());
} else if (max && max.getFullYear() < this.currentYear()) {
this.currentMonth.set(max.getMonth());
this.currentYear.set(max.getFullYear());
}
});
// Effect to automatically select 'Custom Range' when user picks dates manually
effect(() => {
const startDate = this._selectedStartDate();
const endDate = this._selectedEndDate();
if (startDate || endDate) { // If any date is selected manually
const isPresetMatch = this.presetRanges().some(preset => {
if (preset.isCustom) return false;
// Temporarily apply preset to check if it matches current selection
const tempStart = this._selectedStartDate();
const tempEnd = this._selectedEndDate();
preset.handler(); // Execute the handler to set temporary dates
const matches = isSameDay(this._selectedStartDate(), tempStart) && isSameDay(this._selectedEndDate(), tempEnd);
this._selectedStartDate.set(tempStart); // Revert back
this._selectedEndDate.set(tempEnd); // Revert back
return matches;
});
if (!isPresetMatch) {
this.selectedPreset.set('Custom Range');
}
}
});
}
ngOnInit(): void {
// Initialize date picker if no value is set
// For reactive forms, writeValue will handle initial value.
// For standalone, _selectedStartDate will be null initially.
// We want the calendar to open on current month/year if no date is selected.
const today = new Date();
if (!this._selectedStartDate()) {
this.currentMonth.set(today.getMonth());
this.currentYear.set(today.getFullYear());
}
}
// --- ControlValueAccessor Implementation ---
/**
* Writes a new value from the form model into the component.
* @param value The value from the form model.
*/
public writeValue(value: string | [string, string] | null): void {
this._previousValue = value; // Store for reset functionality
if (this.rangeMode()) {
if (Array.isArray(value) && value.length === 2) {
this._selectedStartDate.set(parseDate(value[0]));
this._selectedEndDate.set(parseDate(value[1]));
} else {
this._selectedStartDate.set(null);
this._selectedEndDate.set(null);
}
} else {
this._selectedStartDate.set(parseDate(value as string));
this._selectedEndDate.set(null); // Ensure end date is null in single mode
}
}
/**
* Registers a callback function that should be called when the control's value changes.
* @param fn The callback function.
*/
public registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Registers a callback function that should be called when the control receives a touch event.
* @param fn The callback function.
*/
public registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
/**
* Sets the disabled state of the control.
* @param isDisabled True if the control should be disabled, false otherwise.
*/
public setDisabledState(isDisabled: boolean): void {
this._isDisabled.set(isDisabled);
}
// --- Calendar Open/Close Logic ---
public toggleCalendar(): void {
if (this._isDisabled()) return;
if (this.showCalendar()) {
this.closeCalendar();
} else {
this.openCalendar();
}
}
public openCalendar(): void {
if (this._isDisabled()) return;
this.showCalendar.set(true);
// When opening, reset the current month/year to selected date if any,
// otherwise to today.
const dateToDisplay = this._selectedStartDate() || new Date();
this.currentMonth.set(dateToDisplay.getMonth());
this.currentYear.set(dateToDisplay.getFullYear());
this.showMonthPicker.set(false);
this.showYearPicker.set(false);
this._onTouched(); // Mark as touched on open
}
public closeCalendar(): void {
this.showCalendar.set(false);
this.showMonthPicker.set(false);
this.showYearPicker.set(false);
this._hoverDate.set(null);
}
/**
* Handles clicks outside the component to close the calendar.
*/
@HostListener('document:click', ['$event'])
private onClickOutside(event: MouseEvent): void {
if (!this.elementRef.nativeElement.contains(event.target) && this.showCalendar()) {
// If clicking outside, and calendar is open, cancel and close.
this.cancelSelection();
}
}
/**
* Prevents calendar from closing when input field loses focus due to click inside calendar.
*/
public onInputBlur(): void {
// This is a common issue: input blur fires before click on calendar.
// We defer the onTouched call to ensure it's not triggered prematurely
// by clicking elements *within* the datepicker.
// If the calendar stays open, _onTouched will be called later when closing or saving.
if (!this.showCalendar()) {
this._onTouched();
}
}
// --- Calendar Navigation ---
public goToPrevMonth(): void {
if (this.isPrevMonthDisabled()) return;
const newDate = addMonths(
new Date(this.currentYear(), this.currentMonth(), 1),
-1
);
this.currentMonth.set(newDate.getMonth());
this.currentYear.set(newDate.getFullYear());
}
public goToNextMonth(): void {
if (this.isNextMonthDisabled()) return;
const newDate = addMonths(
new Date(this.currentYear(), this.currentMonth(), 1),
1
);
this.currentMonth.set(newDate.getMonth());
this.currentYear.set(newDate.getFullYear());
}
public selectMonth(month: number): void {
this.currentMonth.set(month);
this.showMonthPicker.set(false);
this._onTouched(); // Mark as touched when month is selected
}
public selectYear(year: number): void {
this.currentYear.set(year);
this.showYearPicker.set(false);
this._onTouched(); // Mark as touched when year is selected
}
// --- Date Selection Logic ---
/**
* Handles a click on a calendar day.
* @param day The CalendarDay object that was clicked.
*/
public onDayClick(day: CalendarDay): void {
if (day.isDisabled) return;
this.selectedPreset.set(null); // Any manual selection makes it a custom range
if (this.rangeMode()) {
const currentStart = this._selectedStartDate();
const currentEnd = this._selectedEndDate();
if (!currentStart || currentEnd) {
// If no start date or both dates are already selected, start new range
this._selectedStartDate.set(day.date);
this._selectedEndDate.set(null);
} else {
// Start date is selected, now select end date
if (day.date < currentStart) {
// If new date is before start date, swap them
this._selectedEndDate.set(currentStart);
this._selectedStartDate.set(day.date);
} else {
this._selectedEndDate.set(day.date);
}
}
} else {
this._selectedStartDate.set(day.date);
this._selectedEndDate.set(null);
this.saveSelection(); // In single mode, save and close immediately
}
this._onTouched(); // Mark as touched
}
/**
* Handles mouse enter event on a calendar day for hover range preview.
* @param day The CalendarDay object being hovered over.
*/
public onDayMouseEnter(day: CalendarDay): void {
if (this.rangeMode() && this._selectedStartDate() && !this._selectedEndDate()) {
this._hoverDate.set(day.date);
}
}
/**
* Handles mouse leave event from the calendar grid.
*/
public onDayMouseLeave(): void {
if (this.rangeMode() && !this._selectedEndDate()) {
this._hoverDate.set(null);
}
}
// --- Date Status Checkers (for computed signals) ---
private _isDateDisabled(date: Date): boolean {
const min = this.minDate();
const max = this.maxDate();
const normalizedDate = startOfDay(date);
if (min && normalizedDate < startOfDay(min)) {
return true;
}
if (max && normalizedDate > endOfDay(max)) {
return true;
}
return false;
}
private _isDateInSelectedRange(date: Date): boolean {
if (!this.rangeMode() || !this._selectedStartDate() || !this._selectedEndDate()) {
return false;
}
const start = startOfDay(this._selectedStartDate()!);
const end = endOfDay(this._selectedEndDate()!);
const current = startOfDay(date);
return current >= start && current <= end;
}
private _isDateInHoverRange(date: Date): boolean {
if (!this.rangeMode() || !this._selectedStartDate() || this._selectedEndDate() || !this._hoverDate()) {
return false;
}
const start = startOfDay(this._selectedStartDate()!);
const hover = startOfDay(this._hoverDate()!);
// Determine the effective start and end for hover range display
const effectiveStart = startOfDay(Math.min(start.getTime(), hover.getTime()));
const effectiveEnd = endOfDay(Math.max(start.getTime(), hover.getTime()));
const current = startOfDay(date);
return current >= effectiveStart && current <= effectiveEnd;
}
// --- Preset Range Handlers ---
public handlePresetClick(handler: () => void, isCustom: boolean = false, label: string): void {
handler(); // Execute the preset logic
if (!isCustom) {
this.selectedPreset.set(label);
if (!this.rangeMode()) { // If not range mode, presets imply a single date, so save and close
this.saveSelection();
}
} else {
this.selectedPreset.set(label);
}
this._onTouched(); // Mark as touched
}
private selectToday(): void {
const today = new Date();
this._selectedStartDate.set(today);
this._selectedEndDate.set(null); // Ensure no end date for single or simple preset
if (this.rangeMode()) { // In range mode, Today is a single point, so clear end date.
this._selectedEndDate.set(today); // For "Today" preset, start and end are the same
}
}
private selectYesterday(): void {
const yesterday = addDays(new Date(), -1);
this._selectedStartDate.set(yesterday);
this._selectedEndDate.set(null);
if (this.rangeMode()) {
this._selectedEndDate.set(yesterday);
}
}
private selectLast7Days(): void {
const today = new Date();
this._selectedStartDate.set(addDays(today, -6)); // Today - 6 days = last 7 days including today
this._selectedEndDate.set(today);
}
private selectLast30Days(): void {
const today = new Date();
this._selectedStartDate.set(addDays(today, -29)); // Today - 29 days = last 30 days including today
this._selectedEndDate.set(today);
}
private selectThisMonth(): void {
const today = new Date();
const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
this._selectedStartDate.set(firstDay);
this._selectedEndDate.set(lastDay);
}
private selectLastMonth(): void {
const today = new Date();
const firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
const lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
this._selectedStartDate.set(firstDayOfLastMonth);
this._selectedEndDate.set(lastDayOfLastMonth);
}
private selectCustomRange(): void {
this._selectedStartDate.set(null);
this._selectedEndDate.set(null);
}
// --- Footer Button Actions ---
public resetSelection(): void {
// Revert to the state before the calendar was opened, or last saved state
this.writeValue(this._previousValue);
this.selectedPreset.set(null); // Clear preset if custom
this._onTouched();
}
public cancelSelection(): void {
this.resetSelection(); // Cancel implies reverting to previous state
this.closeCalendar();
}
public saveSelection(): void {
let valueToEmit: string | [string, string] | null = null;
if (this.rangeMode()) {
const start = this._selectedStartDate();
const end = this._selectedEndDate();
if (start && end) {
// Ensure start is always before end for storage
const effectiveStart = startOfDay(Math.min(start.getTime(), end.getTime()));
const effectiveEnd = endOfDay(Math.max(start.getTime(), end.getTime()));
valueToEmit = [formatDate(effectiveStart), formatDate(effectiveEnd)];
} else if (start) {
// If only start date is selected in range mode, emit it as single day range
valueToEmit = [formatDate(start), formatDate(start)];
} else {
valueToEmit = null;
}
} else {
valueToEmit = formatDate(this._selectedStartDate());
}
this._previousValue = valueToEmit; // Update previous value on save
this._onChange(valueToEmit);
this.closeCalendar();
}
}
import { Component, signal } from '@angular/core';
import { DatepickerComponent } from './components/datepicker/datepicker.component';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [DatepickerComponent, ReactiveFormsModule, CommonModule],
template: `
<div class="container">
<h1>Angular Custom Date Picker</h1>
<!-- Standalone Mode (Single Date) -->
<h2>Single Date Picker (Standalone)</h2>
<gsd-datepicker></gsd-datepicker>
<p>Selected Value (internal): {{ singleDateValue() | json }}</p>
<button (click)="setSingleDate()">Set Today</button>
<button (click)="clearSingleDate()">Clear</button>
<hr />
<!-- Reactive Forms (Single Date) -->
<h2>Single Date Picker (Reactive Forms)</h2>
<form [formGroup]="singleDateForm">
<gsd-datepicker formControlName="mySingleDate"></gsd-datepicker>
</form>
<p>Form Value: {{ singleDateForm.value | json }}</p>
<button (click)="patchSingleDate()">Patch '15-03-2024'</button>
<button (click)="disableSingleDate()">Disable/Enable</button>
<hr />
<!-- Reactive Forms (Range Mode) -->
<h2>Date Range Picker (Reactive Forms)</h2>
<form [formGroup]="rangeDateForm">
<gsd-datepicker
[rangeMode]="true"
[minDate]="minRangeDate()"
[maxDate]="maxRangeDate()"
formControlName="myRange"
></gsd-datepicker>
</form>
<p>Form Value: {{ rangeDateForm.value | json }}</p>
<button (click)="patchRangeDate()">Patch '01-01-2024' to '07-01-2024'</button>
<button (click)="setRangeMinMax()">Set Min/Max Dates</button>
<button (click)="clearRangeMinMax()">Clear Min/Max Dates</button>
<button (click)="disableRangeDate()">Disable/Enable</button>
<hr />
<!-- NgModel (Single Date) -->
<h2>Single Date Picker (NgModel)</h2>
<gsd-datepicker [(ngModel)]="ngModelSingleDate" name="ngModelSingle"></gsd-datepicker>
<p>NgModel Value: {{ ngModelSingleDate | json }}</p>
<button (click)="setNgModelSingle()">Set '10-10-2023'</button>
<button (click)="clearNgModelSingle()">Clear NgModel</button>
<hr />
<!-- NgModel (Range Date) -->
<h2>Date Range Picker (NgModel)</h2>
<gsd-datepicker [rangeMode]="true" [(ngModel)]="ngModelRangeDate" name="ngModelRange"></gsd-datepicker>
<p>NgModel Value: {{ ngModelRangeDate | json }}</p>
<button (click)="setNgModelRange()">Set '05-02-2024' to '15-02-2024'</button>
<button (click)="clearNgModelRange()">Clear NgModel</button>
</div>
`,
styles: `
.container {
padding: 20px;
max-width: 900px;
margin: 0 auto;
}
h1, h2 {
color: #333;
margin-bottom: 20px;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
gsd-datepicker {
margin-bottom: 20px;
display: block; /* Ensure it takes full width for demo */
}
button {
padding: 8px 15px;
margin-right: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
&:hover {
background-color: #0056b3;
}
&:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
}
p {
margin-top: 10px;
font-family: monospace;
background-color: #f8f8f8;
padding: 5px 10px;
border-radius: 3px;
}
hr {
margin: 40px 0;
border: 0;
border-top: 1px solid #eee;
}
`,
})
export class AppComponent {
// --- Standalone (Single Date) ---
public singleDateValue = signal<string | null>(null);
setSingleDate() {
const today = new Date();
const day = String(today.getDate()).padStart(2, '0');
const month = String(today.getMonth() + 1).padStart(2, '0');
const year = today.getFullYear();
this.singleDateValue.set(`${day}-${month}-${year}`);
}
clearSingleDate() {
this.singleDateValue.set(null);
}
// --- Reactive Forms (Single Date) ---
public singleDateForm = new FormGroup({
mySingleDate: new FormControl<string | null>(null),
});
patchSingleDate() {
this.singleDateForm.patchValue({ mySingleDate: '15-03-2024' });
}
disableSingleDate() {
if (this.singleDateForm.get('mySingleDate')?.disabled) {
this.singleDateForm.get('mySingleDate')?.enable();
} else {
this.singleDateForm.get('mySingleDate')?.disable();
}
}
// --- Reactive Forms (Range Mode) ---
public minRangeDate = signal<Date | null>(null);
public maxRangeDate = signal<Date | null>(null);
public rangeDateForm = new FormGroup({
myRange: new FormControl<[string, string] | null>(null),
});
patchRangeDate() {
this.rangeDateForm.patchValue({
myRange: ['01-01-2024', '07-01-2024'],
});
}
setRangeMinMax() {
this.minRangeDate.set(new Date(2023, 0, 1)); // Jan 1, 2023
this.maxRangeDate.set(new Date(2024, 11, 31)); // Dec 31, 2024
}
clearRangeMinMax() {
this.minRangeDate.set(null);
this.maxRangeDate.set(null);
}
disableRangeDate() {
if (this.rangeDateForm.get('myRange')?.disabled) {
this.rangeDateForm.get('myRange')?.enable();
} else {
this.rangeDateForm.get('myRange')?.disable();
}
}
// --- NgModel (Single Date) ---
public ngModelSingleDate: string | null = null;
setNgModelSingle() {
this.ngModelSingleDate = '10-10-2023';
}
clearNgModelSingle() {
this.ngModelSingleDate = null;
}
// --- NgModel (Range Date) ---
public ngModelRangeDate: [string, string] | null = null;
setNgModelRange() {
this.ngModelRangeDate = ['05-02-2024', '15-02-2024'];
}
clearNgModelRange() {
this.ngModelRangeDate = null;
}
}