The DatePicker component provides a user-friendly calendar interface for selecting dates. It includes built-in support for minimum and maximum date constraints, making it perfect for birthdays, appointments, and any date-based input.
import { Validators } from '@angular/forms';const birthdayPicker = new DatePicker( 'birthday', 'Date of Birth').apply({ minDate: new Date(1900, 0, 1), // January 1, 1900 maxDate: new Date(), // Today (can't be in the future) icon: 'cake', validator: Validators.required, hint: 'You must be 18 or older'});
const eventPicker = new DatePicker( 'eventDate', 'Event Date').apply({ minDate: new Date(), // Today or later maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 2)), // Up to 2 years ahead icon: 'event', validator: Validators.required, hint: 'Select a date within the next 2 years'});
const lastVisitPicker = new DatePicker( 'lastVisit', 'Last Visit Date').apply({ maxDate: new Date(), // Today or earlier icon: 'history', hint: 'When did you last visit?'});
import { AbstractControl, ValidationErrors } from '@angular/forms';// Must be at least 18 years agofunction ageValidator(control: AbstractControl): ValidationErrors | null { if (!control.value) return null; const birthDate = new Date(control.value); const today = new Date(); const age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } if (age < 18) { return { underAge: true }; } return null;}const birthdayPicker = new DatePicker('birthday', 'Date of Birth').apply({ validator: [Validators.required, ageValidator], errorMessage: 'You must be at least 18 years old', maxDate: new Date()});
function weekdayValidator(control: AbstractControl): ValidationErrors | null { if (!control.value) return null; const date = new Date(control.value); const day = date.getDay(); // 0 = Sunday, 6 = Saturday if (day === 0 || day === 6) { return { weekendDate: true }; } return null;}const appointmentPicker = new DatePicker('appointment', 'Appointment').apply({ validator: [Validators.required, weekdayValidator], errorMessage: 'Appointments are only available on weekdays', minDate: new Date()});
// Get the date value from formconst formData = formStructure.getValue();const selectedDate = formData.birthday; // Date object or string// Convert to Date object if neededconst date = new Date(selectedDate);console.log('Year:', date.getFullYear());console.log('Month:', date.getMonth() + 1); // Months are 0-indexedconsole.log('Day:', date.getDate());
// Set specific dateformStructure.patchValue({ birthday: new Date(1990, 0, 15) // January 15, 1990});// Set to todayformStructure.patchValue({ appointment: new Date()});// Set to 30 days from nowconst futureDate = new Date();futureDate.setDate(futureDate.getDate() + 30);formStructure.patchValue({ deadline: futureDate});