syncfusion-angular-calendars
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion Angular Calendars
实现Syncfusion Angular日历组件
Calendars
日历组件
A comprehensive guide for implementing the Syncfusion Essential JS 2 Calendar component in Angular applications. Learn to create date pickers, manage calendar views, handle events, and customize styling.
本指南详细介绍如何在Angular应用中实现Syncfusion Essential JS 2 Calendar组件,包括创建日期选择器、管理日历视图、处理事件和自定义样式。
Calendar Overview
日历组件概述
The Syncfusion Angular Calendar component is a date selection widget that provides:
- Multiple calendar views: Month (default), Year, and Decade views with smooth navigation
- Date selection modes: Single date or multiple dates with property
isMultiSelection - Navigation control: method for programmatic view switching
navigateTo() - Date manipulation methods: and
addDate()for multi-selection managementremoveDate() - Comprehensive event system: change, created, navigated, renderDayCell, destroyed events
- Localization support: Locale-specific formatting, day header formats, first day of week
- Accessibility: Full WCAG 2.2 compliance, keyboard navigation, RTL support
- Rich customization: CSS classes, custom rendering, day cell customization
- Persistence: Optional state persistence across page reloads
Package:
@syncfusion/ej2-angular-calendarsSyncfusion Angular Calendar组件是一款日期选择小部件,具备以下功能:
- 多日历视图:默认的月视图,以及年视图、十年视图,支持流畅导航
- 日期选择模式:通过属性支持单日期或多日期选择
isMultiSelection - 导航控制:使用方法实现程序化视图切换
navigateTo() - 日期操作方法:和
addDate()用于管理多日期选择removeDate() - 完善的事件系统:change、created、navigated、renderDayCell、destroyed等事件
- 本地化支持:特定区域的格式、日头格式、一周起始日设置
- 无障碍访问:完全符合WCAG 2.2标准,支持键盘导航、RTL布局
- 丰富的自定义:CSS类、自定义渲染、日期单元格定制
- 状态持久化:支持跨页面重载保留组件状态
包依赖:
@syncfusion/ej2-angular-calendarsDocumentation Navigation
文档导航
Read the following references based on your specific needs:
根据你的需求阅读以下参考文档:
Getting Started
快速入门
📄 Read: references/getting-started.md
- Package installation and module setup
- CSS theme imports and dependencies
- Basic calendar implementation
- Component initialization in Angular
- Running and testing setup
📄 阅读:references/getting-started.md
- 包安装与模块配置
- CSS主题导入与依赖管理
- 基础日历组件实现
- Angular中的组件初始化
- 运行与测试环境搭建
Calendar Views
日历视图
📄 Read: references/calendar-views.md
- Month view (default display)
- Year view implementation
- Decade view implementation
- View navigation and transitions
- property usage
start - property for restricting views
depth
📄 阅读:references/calendar-views.md
- 月视图(默认显示)
- 年视图实现
- 十年视图实现
- 视图导航与过渡
- 属性的使用
start - 属性限制视图层级
depth
Date Selection
日期选择
📄 Read: references/date-selection.md
- Single date selection
- Multiple date selection ()
isMultiSelection - property for single dates
value - array for multiple dates
values - Min/max date constraints
- Date range validation
📄 阅读:references/date-selection.md
- 单日期选择
- 多日期选择()
isMultiSelection - 单日期对应的属性
value - 多日期对应的数组
values - 最小/最大日期约束
- 日期范围验证
Events & Methods
事件与方法
📄 Read: references/events-and-methods.md
- Event handlers (change, created, navigated, renderDayCell, destroyed)
- method for multi-selection
addDate() - method for multi-selection
removeDate() - for programmatic navigation
navigateTo() - to get active view
currentView() - to retrieve persistence data
getPersistData() - to destroy the calendar widget
destroy() - RenderDayCell for custom day styling
📄 阅读:references/events-and-methods.md
- 事件处理器(change、created、navigated、renderDayCell、destroyed)
- 多日期选择的方法
addDate() - 多日期选择的方法
removeDate() - 程序化导航的方法
navigateTo() - 获取当前视图的方法
currentView() - 获取持久化数据的方法
getPersistData() - 销毁日历小部件的方法
destroy() - 自定义日期单元格样式的RenderDayCell事件
Calendar Navigation
日历导航
📄 Read: references/calendar-navigation.md
- Month navigation controls
- Year and Decade view switching
- Today button ()
showTodayButton - property
firstDayOfWeek - Week number display ()
weekNumber - Keyboard shortcuts and navigation
📄 阅读:references/calendar-navigation.md
- 月份导航控件
- 年视图与十年视图切换
- 今日按钮()
showTodayButton - 属性
firstDayOfWeek - 周数显示()
weekNumber - 键盘快捷键与导航
Accessibility & Globalization
无障碍访问与全球化
📄 Read: references/accessibility-and-globalization.md
- WCAG 2.2 and Section 508 compliance
- WAI-ARIA attributes and roles
- Keyboard navigation (arrows, enter, spacebar)
- Screen reader compatibility
- Localization (locale property)
- Day header formats (Short, Narrow, Abbreviated, Wide)
- RTL (Right-to-Left) support
📄 阅读:references/accessibility-and-globalization.md
- 符合WCAG 2.2和Section 508标准
- WAI-ARIA属性与角色
- 键盘导航(箭头、回车、空格)
- 屏幕阅读器兼容性
- 本地化(locale属性)
- 日头格式(Short、Narrow、Abbreviated、Wide)
- RTL(从右到左)布局支持
Styling & Customization
样式与自定义
📄 Read: references/styling-and-customization.md
- CSS class customization (.e-calendar, .e-day-cell, .e-selected)
- Theme selection (Material, Bootstrap, Tailwind, Fabric)
- Dark mode implementation
- Custom day cell styling via renderDayCell
- Disabled dates styling
- Hover and focus states
📄 阅读:references/styling-and-customization.md
- CSS类自定义(.e-calendar、.e-day-cell、.e-selected)
- 主题选择(Material、Bootstrap、Tailwind、Fabric)
- 深色模式实现
- 通过renderDayCell自定义日期单元格样式
- 禁用日期的样式设置
- 悬停与焦点状态
API Reference
API参考
📄 Read: references/api-reference.md
- Complete property reference (value, values, isMultiSelection, min, max, start, depth, showTodayButton, locale, dayHeaderFormat, weekNumber, weekRule, firstDayOfWeek, cssClass, enableRtl, enabled, calendarMode, keyConfigs, enablePersistence, serverTimezoneOffset)
- All method signatures with examples (addDate, removeDate, navigateTo, currentView, getPersistData, destroy)
- Event argument types (ChangedEventArgs, NavigatedEventArgs, RenderDayCellEventArgs)
- Key configurations for keyboard shortcuts
- Calendar modes (Gregorian, Islamic)
- Return types and descriptions
📄 阅读:references/api-reference.md
- 完整属性参考(value、values、isMultiSelection、min、max、start、depth、showTodayButton、locale、dayHeaderFormat、weekNumber、weekRule、firstDayOfWeek、cssClass、enableRtl、enabled、calendarMode、keyConfigs、enablePersistence、serverTimezoneOffset)
- 所有方法签名及示例(addDate、removeDate、navigateTo、currentView、getPersistData、destroy)
- 事件参数类型(ChangedEventArgs、NavigatedEventArgs、RenderDayCellEventArgs)
- 键盘快捷键的配置
- 日历模式(Gregorian、Islamic)
- 返回类型与描述
Quick Start Example
快速入门示例
typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangedEventArgs } from '@syncfusion/ej2-calendars';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Single date selection
selectedDate: Date = new Date();
// Multiple date selection
selectedDates: Date[] = [
new Date(2026, 2, 15),
new Date(2026, 2, 20),
new Date(2026, 2, 25)
];
// Calendar configuration
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
// Event handler
onCalendarChange(args: ChangedEventArgs): void {
console.log('Selected date:', args.value);
}
}html
<!-- app.component.html -->
<div style="padding: 20px; font-family: Arial, sans-serif;">
<h2>Single Date Selection</h2>
<ejs-calendar
[(ngModel)]="selectedDate"
[min]="minDate"
[max]="maxDate"
(change)="onCalendarChange($event)">
</ejs-calendar>
<p>Selected: {{ selectedDate | date:'medium' }}</p>
<h2>Multiple Date Selection</h2>
<ejs-calendar
[(ngModel)]="selectedDates"
[isMultiSelection]="true"
[showTodayButton]="true">
</ejs-calendar>
<p>Selected dates: {{ selectedDates.length }} dates</p>
</div>css
/* app.component.css */
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';
:host ::ng-deep .e-calendar {
margin: 20px 0;
}
:host ::ng-deep .e-selected {
background-color: #3f51b5;
color: white;
}typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangedEventArgs } from '@syncfusion/ej2-calendars';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// 单日期选择
selectedDate: Date = new Date();
// 多日期选择
selectedDates: Date[] = [
new Date(2026, 2, 15),
new Date(2026, 2, 20),
new Date(2026, 2, 25)
];
// 日历配置
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
// 事件处理器
onCalendarChange(args: ChangedEventArgs): void {
console.log('Selected date:', args.value);
}
}html
<!-- app.component.html -->
<div style="padding: 20px; font-family: Arial, sans-serif;">
<h2>单日期选择</h2>
<ejs-calendar
[(ngModel)]="selectedDate"
[min]="minDate"
[max]="maxDate"
(change)="onCalendarChange($event)">
</ejs-calendar>
<p>已选择: {{ selectedDate | date:'medium' }}</p>
<h2>多日期选择</h2>
<ejs-calendar
[(ngModel)]="selectedDates"
[isMultiSelection]="true"
[showTodayButton]="true">
</ejs-calendar>
<p>已选择日期数: {{ selectedDates.length }} 个</p>
</div>css
/* app.component.css */
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';
:host ::ng-deep .e-calendar {
margin: 20px 0;
}
:host ::ng-deep .e-selected {
background-color: #3f51b5;
color: white;
}Common Patterns
常见模式
Pattern 1: Custom Date Range (Two Calendar Instances)
模式1:自定义日期范围(两个日历实例)
The Calendar component does not have built-in range selection. Use two separate Calendar instances with / constraints and the event to implement a custom date range picker:
minmaxchangetypescript
export class AppComponent {
startDate: Date = new Date();
endDate: Date = new Date();
onStartDateChange(args: ChangedEventArgs): void {
this.startDate = args.value;
// Ensure end date is not before start date
if (this.endDate < this.startDate) {
this.endDate = this.startDate;
}
}
onEndDateChange(args: ChangedEventArgs): void {
this.endDate = args.value;
}
getDaysInRange(): number {
const timeDiff = this.endDate.getTime() - this.startDate.getTime();
return Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
}
}html
<!-- Two separate Calendar instances for range selection -->
<ejs-calendar [(ngModel)]="startDate" (change)="onStartDateChange($event)"></ejs-calendar>
<ejs-calendar [(ngModel)]="endDate" [min]="startDate" (change)="onEndDateChange($event)"></ejs-calendar>Calendar组件没有内置的范围选择功能,可使用两个独立的Calendar实例,结合/约束和事件实现自定义日期范围选择器:
minmaxchangetypescript
export class AppComponent {
startDate: Date = new Date();
endDate: Date = new Date();
onStartDateChange(args: ChangedEventArgs): void {
this.startDate = args.value;
// 确保结束日期不早于开始日期
if (this.endDate < this.startDate) {
this.endDate = this.startDate;
}
}
onEndDateChange(args: ChangedEventArgs): void {
this.endDate = args.value;
}
getDaysInRange(): number {
const timeDiff = this.endDate.getTime() - this.startDate.getTime();
return Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
}
}html
<!-- 两个独立的Calendar实例用于范围选择 -->
<ejs-calendar [(ngModel)]="startDate" (change)="onStartDateChange($event)"></ejs-calendar>
<ejs-calendar [(ngModel)]="endDate" [min]="startDate" (change)="onEndDateChange($event)"></ejs-calendar>Pattern 2: Calendar with Disabled Dates
模式2:包含禁用日期的日历
Disable specific dates (weekends, holidays) using renderDayCell event:
typescript
export class AppComponent {
holidays: Date[] = [
new Date(2026, 11, 25), // Christmas
new Date(2026, 0, 1), // New Year
];
onRenderDayCell(args: RenderDayCellEventArgs): void {
// Disable weekends
if (args.date.getDay() === 0 || args.date.getDay() === 6) {
args.isDisabled = true;
}
// Disable holidays
if (this.isHoliday(args.date)) {
args.isDisabled = true;
}
}
private isHoliday(date: Date): boolean {
return this.holidays.some(holiday =>
holiday.toDateString() === date.toDateString()
);
}
}使用renderDayCell事件禁用特定日期(周末、节假日):
typescript
export class AppComponent {
holidays: Date[] = [
new Date(2026, 11, 25), // 圣诞节
new Date(2026, 0, 1), // 新年
];
onRenderDayCell(args: RenderDayCellEventArgs): void {
// 禁用周末
if (args.date.getDay() === 0 || args.date.getDay() === 6) {
args.isDisabled = true;
}
// 禁用节假日
if (this.isHoliday(args.date)) {
args.isDisabled = true;
}
}
private isHoliday(date: Date): boolean {
return this.holidays.some(holiday =>
holiday.toDateString() === date.toDateString()
);
}
}Pattern 3: Multi-Selection with Add/Remove
模式3:添加/移除多日期选择
Manage multiple selected dates programmatically:
typescript
export class AppComponent {
@ViewChild('calendar') calendarRef!: CalendarComponent;
selectedDates: Date[] = [];
addDateToSelection(date: Date): void {
// Check if already selected
if (!this.selectedDates.some(d =>
d.toDateString() === date.toDateString())) {
this.calendarRef.addDate(date);
}
}
removeDateFromSelection(date: Date): void {
this.calendarRef.removeDate(date);
}
clearAllDates(): void {
if (this.selectedDates.length > 0) {
this.calendarRef.removeDate(this.selectedDates);
}
}
}程序化管理多个选中日期:
typescript
export class AppComponent {
@ViewChild('calendar') calendarRef!: CalendarComponent;
selectedDates: Date[] = [];
addDateToSelection(date: Date): void {
// 检查是否已选中
if (!this.selectedDates.some(d =>
d.toDateString() === date.toDateString())) {
this.calendarRef.addDate(date);
}
}
removeDateFromSelection(date: Date): void {
this.calendarRef.removeDate(date);
}
clearAllDates(): void {
if (this.selectedDates.length > 0) {
this.calendarRef.removeDate(this.selectedDates);
}
}
}Pattern 4: Year/Decade View Navigation
模式4:年/十年视图导航
Implement navigation to different calendar views:
typescript
export class AppComponent {
@ViewChild('calendar') calendarRef!: CalendarComponent;
navigateToYear(year: number): void {
const dateInYear = new Date(year, 0, 1);
this.calendarRef.navigateTo('Year', dateInYear);
}
navigateToDecade(startYear: number): void {
const dateInDecade = new Date(startYear, 0, 1);
this.calendarRef.navigateTo('Decade', dateInDecade);
}
getCurrentView(): string {
return this.calendarRef.currentView();
}
}实现不同日历视图的导航:
typescript
export class AppComponent {
@ViewChild('calendar') calendarRef!: CalendarComponent;
navigateToYear(year: number): void {
const dateInYear = new Date(year, 0, 1);
this.calendarRef.navigateTo('Year', dateInYear);
}
navigateToDecade(startYear: number): void {
const dateInDecade = new Date(startYear, 0, 1);
this.calendarRef.navigateTo('Decade', dateInDecade);
}
getCurrentView(): string {
return this.calendarRef.currentView();
}
}Pattern 5: Reactive Form Integration
模式5:响应式表单集成
Integrate Calendar with Angular Reactive Forms:
typescript
export class AppComponent implements OnInit {
dateForm: FormGroup;
constructor(private fb: FormBuilder) {
this.dateForm = this.fb.group({
eventDate: [new Date(), Validators.required],
eventName: ['', Validators.required]
});
}
ngOnInit(): void {
// Subscribe to date changes
this.dateForm.get('eventDate')?.valueChanges.subscribe(date => {
console.log('Event date changed:', date);
});
}
submitForm(): void {
if (this.dateForm.valid) {
console.log('Form values:', this.dateForm.value);
}
}
}html
<form [formGroup]="dateForm" (ngSubmit)="submitForm()">
<div>
<label for="eventDate">Event Date:</label>
<ejs-calendar
id="eventDate"
formControlName="eventDate">
</ejs-calendar>
</div>
<div>
<label for="eventName">Event Name:</label>
<input
id="eventName"
type="text"
formControlName="eventName">
</div>
<button type="submit" [disabled]="!dateForm.valid">Submit</button>
</form>将Calendar与Angular响应式表单集成:
typescript
export class AppComponent implements OnInit {
dateForm: FormGroup;
constructor(private fb: FormBuilder) {
this.dateForm = this.fb.group({
eventDate: [new Date(), Validators.required],
eventName: ['', Validators.required]
});
}
ngOnInit(): void {
// 订阅日期变化
this.dateForm.get('eventDate')?.valueChanges.subscribe(date => {
console.log('Event date changed:', date);
});
}
submitForm(): void {
if (this.dateForm.valid) {
console.log('Form values:', this.dateForm.value);
}
}
}html
<form [formGroup]="dateForm" (ngSubmit)="submitForm()">
<div>
<label for="eventDate">活动日期:</label>
<ejs-calendar
id="eventDate"
formControlName="eventDate">
</ejs-calendar>
</div>
<div>
<label for="eventName">活动名称:</label>
<input
id="eventName"
type="text"
formControlName="eventName">
</div>
<button type="submit" [disabled]="!dateForm.valid">提交</button>
</form>Key Props Reference
关键属性参考
| Prop | Type | Description | Example |
|---|---|---|---|
| | Single selected date | |
| | Multiple selected dates | |
| | Enable multiple date selection | |
| | Minimum selectable date | |
| | Maximum selectable date | |
| | Initial view (Month/Year/Decade) | |
| | Maximum view level | |
| | Display today button | |
| | Culture/language code | |
| | Day format (Short/Narrow/Abbreviated/Wide) | |
| | Show week numbers | |
| | Rule for first week of year (FirstDay/FirstFullWeek/FirstFourDayWeek) | |
| | First day (0=Sunday, 1=Monday) | |
| | Custom CSS classes | |
| | Enable RTL layout | |
| | Enable/disable component | |
| | Calendar mode (Gregorian/Islamic) | |
| | Custom keyboard shortcuts | |
| | Persist state across page reloads | |
| | Server timezone offset for initial date processing | |
| 属性 | 类型 | 描述 | 示例 |
|---|---|---|---|
| | 单个选中日期 | |
| | 多个选中日期 | |
| | 启用多日期选择 | |
| | 最小可选日期 | |
| | 最大可选日期 | |
| | 初始视图(Month/Year/Decade) | |
| | 最大视图层级 | |
| | 显示今日按钮 | |
| | 区域/语言代码 | |
| | 日格式(Short/Narrow/Abbreviated/Wide) | |
| | 显示周数 | |
| | 一年第一周的规则(FirstDay/FirstFullWeek/FirstFourDayWeek) | |
| | 一周起始日(0=周日,1=周一) | |
| | 自定义CSS类 | |
| | 启用RTL布局 | |
| | 启用/禁用组件 | |
| | 日历模式(Gregorian/Islamic) | |
| | 自定义键盘快捷键 | |
| | 跨页面重载保留状态 | |
| | 服务器时区偏移(用于初始日期处理) | |
Common Use Cases
常见使用场景
Use Case 1: Event Booking System
- User selects start and end dates for event
- Disable past dates and weekends
- Solution: Combine min/max dates with renderDayCell for disable logic
- Reference: Calendar Views + Events & Methods
Use Case 2: Conference Schedule
- Display multiple highlighted dates (conference days)
- Allow year/decade navigation for planning
- Solution: Use isMultiSelection, highlight dates, navigate between views
- Reference: Date Selection + Calendar Navigation
Use Case 3: Accessible Booking Form
- Calendar integrated in form with keyboard navigation
- Screen reader compatible, WCAG 2.2 compliant
- Solution: Use Reactive Forms + Calendar events
- Reference: Accessibility & Globalization
Use Case 4: International Date Picker
- Support multiple languages and date formats
- Show RTL for Arabic, Hebrew
- Solution: Use locale property and localization
- Reference: Accessibility & Globalization
Use Case 5: Dynamic Date Constraints
- Disable dates based on business logic (availability, holidays)
- Update constraints based on user selections
- Solution: Use renderDayCell with dynamic logic
- Reference: Events & Methods + Calendar Views
场景1:活动预订系统
- 用户选择活动的开始和结束日期
- 禁用过去日期和周末
- 解决方案:结合min/max日期和renderDayCell实现禁用逻辑
- 参考文档:日历视图 + 事件与方法
场景2:会议日程
- 显示多个高亮日期(会议日期)
- 允许年/十年导航进行规划
- 解决方案:使用isMultiSelection、高亮日期、视图导航
- 参考文档:日期选择 + 日历导航
场景3:无障碍预订表单
- 日历集成到表单中,支持键盘导航
- 兼容屏幕阅读器,符合WCAG 2.2标准
- 解决方案:使用响应式表单 + 日历事件
- 参考文档:无障碍访问与全球化
场景4:国际化日期选择器
- 支持多种语言和日期格式
- 为阿拉伯语、希伯来语显示RTL布局
- 解决方案:使用locale属性和本地化配置
- 参考文档:无障碍访问与全球化
场景5:动态日期约束
- 根据业务逻辑(可用性、节假日)禁用日期
- 根据用户选择更新约束
- 解决方案:使用renderDayCell和动态逻辑
- 参考文档:事件与方法 + 日历视图
DatePicker
DatePicker
The Syncfusion Angular DatePicker provides a user-friendly calendar interface for selecting individual dates with support for formatting, validation, date ranges, and complete accessibility (WCAG 2.2). This skill guides you through all essential implementation patterns and advanced features.
Syncfusion Angular DatePicker提供了用户友好的日历界面,用于选择单个日期,支持格式化、验证、日期范围和完整的无障碍访问(符合WCAG 2.2标准)。本指南将带你了解所有核心实现模式和高级功能。
Component Overview
组件概述
The DatePicker combines a text input with a popup calendar picker. Users can type dates directly or use the calendar to select. Key capabilities:
- Date selection via calendar UI or text input
- Multiple date formats (culture-aware, custom patterns)
- Date range validation (min/max, strict mode)
- Input masking for guided date entry
- Multiple calendar views (month → year → decade navigation)
- Accessibility (WCAG 2.2, ARIA, keyboard support, RTL)
- Internationalization (CLDR data, 100+ cultures)
- Form integration (FormValidator, reactive forms, template-driven forms)
DatePicker结合了文本输入框和弹出式日历选择器,用户可以直接输入日期或使用日历选择。核心功能包括:
- 通过日历UI或文本输入框选择日期
- 多种日期格式(区域感知、自定义模式)
- 日期范围验证(min/max、严格模式)
- 输入掩码引导日期输入
- 多日历视图(月 → 年 → 十年导航)
- 无障碍访问(WCAG 2.2、ARIA、键盘支持、RTL)
- 国际化(CLDR数据,支持100+区域)
- 表单集成(FormValidator、响应式表单、模板驱动表单)
Documentation and Navigation Guide
文档导航指南
Getting Started
快速入门
📄 Read: references/getting-started.md
- Installation and setup for Angular 21+ standalone architecture
- Package dependencies and imports
- Basic DatePicker implementation
- CSS theme imports
- Minimal working example
📄 阅读:references/getting-started.md
- Angular 21+独立架构的安装与配置
- 包依赖与导入
- 基础DatePicker实现
- CSS主题导入
- 最简可用示例
Date Formats and Parsing
日期格式与解析
📄 Read: references/date-formats-and-parsing.md
- Standard date format patterns (yyyy-MM-dd, dd/MM/yyyy, etc.)
- Culture-specific default formats
- Custom date format creation
- parseDate and formatDate methods
- Dynamic format switching
📄 阅读:references/date-formats-and-parsing.md
- 标准日期格式模式(yyyy-MM-dd、dd/MM/yyyy等)
- 区域特定的默认格式
- 自定义日期格式创建
- parseDate和formatDate方法
- 动态格式切换
Date Range and Validation
日期范围与验证
📄 Read: references/date-range-and-validation.md
- Setting date range constraints (min/max properties)
- Out-of-range date handling and error states
- Null date validation and strictMode
- Invalid date detection
- Real-world date constraint patterns
📄 阅读:references/date-range-and-validation.md
- 设置日期范围约束(min/max属性)
- 超出范围日期的处理与错误状态
- 空日期验证与strictMode
- 无效日期检测
- 实际场景中的日期约束模式
Date Views and Navigation
日期视图与导航
📄 Read: references/date-views-and-navigation.md
- Start view configuration (month/year/decade)
- Depth view restrictions for limited selection
- Navigating between calendar views
- Month and year selection patterns
- Use cases for different view configurations
📄 阅读:references/date-views-and-navigation.md
- 起始视图配置(月/年/十年)
- 限制选择的深度视图
- 日历视图间的导航
- 月份和年份选择模式
- 不同视图配置的使用场景
Masking and Editing
掩码与编辑
📄 Read: references/masking-and-editing.md
- Enabling date input masking for guided entry
- Mask patterns based on date format
- Keyboard navigation in masked input (up/down/left/right arrows)
- Custom mask placeholders
- Locale-aware mask placeholder text
📄 阅读:references/masking-and-editing.md
- 启用日期输入掩码引导输入
- 基于日期格式的掩码模式
- 掩码输入中的键盘导航(上下左右箭头)
- 自定义掩码占位符
- 区域感知的掩码占位符文本
Styling and Customization
样式与自定义
📄 Read: references/styling-and-customization.md
- CSS customization for wrapper and input elements
- DatePicker icon styling and customization
- Full-screen mode on mobile devices
- Placeholder and readonly state customization
- Dark mode and Theme Studio integration
📄 阅读:references/styling-and-customization.md
- 包装器和输入元素的CSS自定义
- DatePicker图标样式与自定义
- 移动设备上的全屏模式
- 占位符和只读状态自定义
- 深色模式与Theme Studio集成
Accessibility and Forms
无障碍访问与表单
📄 Read: references/accessibility-and-forms.md
- WCAG 2.2 compliance and accessibility standards
- ARIA attributes (aria-expanded, aria-disabled, aria-activedescendant)
- Keyboard navigation support (arrow keys, Enter, Escape)
- Screen reader support and semantic markup
- FormValidator integration for date validation
- Reactive forms and template-driven forms patterns
- Custom validation rules
📄 阅读:references/accessibility-and-forms.md
- WCAG 2.2合规性与无障碍标准
- ARIA属性(aria-expanded、aria-disabled、aria-activedescendant)
- 键盘导航支持(箭头键、回车、ESC)
- 屏幕阅读器支持与语义化标记
- FormValidator集成进行日期验证
- 响应式表单和模板驱动表单模式
- 自定义验证规则
Globalization and Localization
全球化与本地化
📄 Read: references/globalization-and-localization.md
- CLDR data loading for culture-specific formatting
- Culture-aware date parsing and formatting
- Locale configuration and L10n setup
- First day of week by culture (week data)
- Right-to-Left (RTL) language support
- Multi-language examples
- Timezone-aware date handling
📄 阅读:references/globalization-and-localization.md
- 加载CLDR数据实现区域特定格式
- 区域感知的日期解析与格式化
- 区域配置与L10n设置
- 按区域设置一周起始日(周数据)
- 从右到左(RTL)语言支持
- 多语言示例
- 时区感知的日期处理
Testing & Quality Assurance
测试与质量保证
📄 Read: references/testing-guide.md
- Unit testing with Jasmine/Karma: parsing, validators, events
- E2E testing with Cypress: calendar interactions, form flows
- Accessibility testing with axe-core and keyboard navigation checks
📄 阅读:references/testing-guide.md
- 使用Jasmine/Karma进行单元测试:解析、验证器、事件
- 使用Cypress进行E2E测试:日历交互、表单流程
- 使用axe-core和键盘导航检查进行无障碍测试
Advanced Patterns
高级模式
📄 Read: references/advanced-patterns.md
- Cascading date pickers (dependent availability)
- Dynamic date ranges driven by business logic
- Blackout/unavailable dates and recurring date handling
- Testing and validation patterns for advanced scenarios
📄 阅读:references/advanced-patterns.md
- 级联日期选择器(依赖可用性)
- 业务逻辑驱动的动态日期范围
- 不可用日期和重复日期处理
- 高级场景的测试与验证模式
Quick Start Example
快速入门示例
Basic DatePicker implementation in Angular 21+ standalone component:
typescript
import { Component } from '@angular/core';
import { DatePickerModule } from '@syncfusion/ej2-angular-calendars';
@Component({
selector: 'app-datepicker-demo',
standalone: true,
imports: [DatePickerModule],
template: `
<ejs-datepicker
placeholder="Select date"
[(ngModel)]="selectedDate"
(change)="onDateChange($event)">
</ejs-datepicker>
<p>Selected: {{ selectedDate | date:'fullDate' }}</p>
`
})
export class DatePickerDemoComponent {
selectedDate: Date | null = null;
onDateChange(event: any) {
console.log('Date changed:', event.value);
}
}Setup Steps:
- Install package
@syncfusion/ej2-angular-calendars - Import in component
DatePickerModule - Add element with properties
<ejs-datepicker> - Bind to component variable with (two-way binding)
[(ngModel)]
What happens:
- DatePicker displays with calendar icon
- Click to open popup calendar
- Select date from calendar or type directly
- Selected date updates component variable
- change event fires on date selection
Angular 21+独立组件中的基础DatePicker实现:
typescript
import { Component } from '@angular/core';
import { DatePickerModule } from '@syncfusion/ej2-angular-calendars';
@Component({
selector: 'app-datepicker-demo',
standalone: true,
imports: [DatePickerModule],
template: `
<ejs-datepicker
placeholder="选择日期"
[(ngModel)]="selectedDate"
(change)="onDateChange($event)">
</ejs-datepicker>
<p>已选择: {{ selectedDate | date:'fullDate' }}</p>
`
})
export class DatePickerDemoComponent {
selectedDate: Date | null = null;
onDateChange(event: any) {
console.log('日期已更改:', event.value);
}
}设置步骤:
- 安装包
@syncfusion/ej2-angular-calendars - 在组件中导入
DatePickerModule - 添加元素并配置属性
<ejs-datepicker> - 使用双向绑定组件变量
[(ngModel)]
实现效果:
- DatePicker显示日历图标
- 点击打开弹出式日历
- 从日历选择日期或直接输入
- 选中日期更新组件变量
- 选择日期时触发change事件
Common Patterns
常见模式
1. Date Range Validation
1. 日期范围验证
Restrict user to select dates between specific start and end dates:
typescript
minDate = new Date(2024, 0, 1); // Jan 1, 2024
maxDate = new Date(2024, 11, 31); // Dec 31, 2024html
<ejs-datepicker
[min]="minDate"
[max]="maxDate"
placeholder="Select date in 2024">
</ejs-datepicker>Use case: Flight booking, hotel reservations, appointment scheduling
限制用户选择特定起始和结束日期之间的日期:
typescript
minDate = new Date(2024, 0, 1); // 2024年1月1日
maxDate = new Date(2024, 11, 31); // 2024年12月31日html
<ejs-datepicker
[min]="minDate"
[max]="maxDate"
placeholder="选择2024年的日期">
</ejs-datepicker>使用场景: 航班预订、酒店预订、预约调度
2. Custom Date Format
2. 自定义日期格式
Display dates in application-specific format:
typescript
dateFormat = 'dd/MM/yyyy'; // European formathtml
<ejs-datepicker
[format]="dateFormat"
placeholder="DD/MM/YYYY">
</ejs-datepicker>以应用特定格式显示日期:
typescript
dateFormat = 'dd/MM/yyyy'; // 欧洲格式html
<ejs-datepicker
[format]="dateFormat"
placeholder="DD/MM/YYYY">
</ejs-datepicker>3. Masked Date Input
3. 掩码日期输入
Guide user with visual masks and arrow key navigation:
html
<ejs-datepicker
[enableMask]="true"
[maskPlaceholder]="'day'"
format="dd/MM/yyyy">
</ejs-datepicker>Keyboard navigation: Up/Down arrows increment/decrement segments, Left/Right navigate between segments
使用视觉掩码和箭头键导航引导用户输入:
html
<ejs-datepicker
[enableMask]="true"
[maskPlaceholder]="'day'"
format="dd/MM/yyyy">
</ejs-datepicker>键盘导航: 上下箭头增减分段值,左右箭头切换分段
4. Date Range Selection (With Min/Max)
4. 日期范围选择(结合Min/Max)
Prevent past dates in booking scenarios:
typescript
minDate = new Date(); // Today
maxDate: Date;
constructor() {
// Set max to 90 days from today
this.maxDate = new Date();
this.maxDate.setDate(this.maxDate.getDate() + 90);
}在预订场景中禁用过去日期:
typescript
minDate = new Date(); // 今日
maxDate: Date;
constructor() {
// 设置最大日期为今日起90天后
this.maxDate = new Date();
this.maxDate.setDate(this.maxDate.getDate() + 90);
}5. Reactive Forms Integration
5. 响应式表单集成
DatePicker with reactive form validation:
typescript
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
export class FormComponent {
form = this.fb.group({
birthDate: [null, [Validators.required]],
});
constructor(private fb: FormBuilder) {}
}html
<form [formGroup]="form">
<ejs-datepicker
formControlName="birthDate"
placeholder="Birth date">
</ejs-datepicker>
<span *ngIf="form.get('birthDate')?.hasError('required')">
Birth date is required
</span>
</form>带响应式表单验证的DatePicker:
typescript
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
export class FormComponent {
form = this.fb.group({
birthDate: [null, [Validators.required]],
});
constructor(private fb: FormBuilder) {}
}html
<form [formGroup]="form">
<ejs-datepicker
formControlName="birthDate"
placeholder="出生日期">
</ejs-datepicker>
<span *ngIf="form.get('birthDate')?.hasError('required')">
出生日期为必填项
</span>
</form>API Reference (Properties, Methods, Events)
API参考(属性、方法、事件)
Properties
属性
| Property | Type | Notes |
|---|---|---|
| boolean | Whether textbox is editable (defaults true) |
| CalendarType | Calendar type (e.g., Gregorian, Islamic) |
| string | Root CSS class for custom styling |
| DayHeaderFormats | Day header format (Short/Narrow/Abbreviated/Wide) |
| CalendarView | Deepest allowed calendar view (Month/Year/Decade) |
| boolean | Enable masked date input |
| boolean | Persist component state between reloads |
| boolean | Enable right-to-left rendering |
| boolean | Enable or disable the component (set |
| number | First day of week (0-6) |
| FloatLabelType | string |
| string|FormatObject | Display format for the value |
| boolean | Popup full-screen mode on mobile |
| { [key:string]: string } | Additional HTML attributes for root element |
| string[]|FormatObject[] | Acceptable input formats for parsing |
| { [key:string]: string } | Custom key action mappings |
| string | Override global culture (e.g., 'en-US') |
| MaskPlaceholderModel | Placeholder text for masked input |
| Date | Maximum selectable date |
| Date | Minimum selectable date |
| boolean | Open popup on input focus |
| string | Input placeholder text |
| boolean | Make input readonly (no typing) |
| number | Server timezone offset in minutes (optional) |
| boolean | Show/hide clear icon |
| boolean | Show/hide today button in popup |
| CalendarView | Initial view when popup opens |
| boolean | Enforce strict parsing/validation |
| Date | Selected date value |
| boolean | Show week numbers in calendar |
| WeekRule | Rule for first week of year |
| number|string | Component width |
| number | Z-index for popup |
| 属性 | 类型 | 说明 |
|---|---|---|
| boolean | 文本框是否可编辑(默认true) |
| CalendarType | 日历类型(如Gregorian、Islamic) |
| string | 用于自定义样式的根CSS类 |
| DayHeaderFormats | 日头格式(Short/Narrow/Abbreviated/Wide) |
| CalendarView | 允许的最深日历视图(Month/Year/Decade) |
| boolean | 启用掩码日期输入 |
| boolean | 跨重载保留组件状态 |
| boolean | 启用从右到左渲染 |
| boolean | 启用或禁用组件(设为 |
| number | 一周起始日(0-6) |
| FloatLabelType | string |
| string|FormatObject | 值的显示格式 |
| boolean | 移动设备上的弹出层全屏模式 |
| { [key:string]: string } | 根元素的额外HTML属性 |
| string[]|FormatObject[] | 可接受的输入解析格式 |
| { [key:string]: string } | 自定义按键动作映射 |
| string | 覆盖全局区域设置(如'en-US') |
| MaskPlaceholderModel | 掩码输入的占位符文本 |
| Date | 最大可选日期 |
| Date | 最小可选日期 |
| boolean | 输入框获焦时打开弹出层 |
| string | 输入框占位符文本 |
| boolean | 设为只读(仅可从弹出层选择) |
| number | 服务器时区偏移(分钟,可选) |
| boolean | 显示/隐藏清除图标 |
| boolean | 显示/隐藏弹出层中的今日按钮 |
| CalendarView | 弹出层打开时的初始视图 |
| boolean | 强制执行严格解析/验证 |
| Date | 选中的日期值 |
| boolean | 在日历中显示周数 |
| WeekRule | 一年第一周的规则 |
| number|string | 组件宽度 |
| number | 弹出层的Z-index |
Methods
方法
- — Returns current calendar view name
currentView() - — Destroy the component instance
destroy() - — Focus the input
focusIn() - — Blur the input
focusOut() - — Returns persisted properties string
getPersistData() - — Hide the calendar popup
hide() - — Navigate to specific view/date
navigateTo(view: CalendarView, date?: Date) - — Remove date(s) from values
removeDate(dates: Date|Date[]) - — Show the calendar popup
show()
- — 返回当前日历视图名称
currentView() - — 销毁组件实例
destroy() - — 聚焦输入框
focusIn() - — 失焦输入框
focusOut() - — 返回持久化属性字符串
getPersistData() - — 隐藏日历弹出层
hide() - — 导航到指定视图/日期
navigateTo(view: CalendarView, date?: Date) - — 从值中移除日期
removeDate(dates: Date|Date[]) - — 显示日历弹出层
show()
Events
事件
- — Emits when input loses focus
blur - — Emits when the value changes (provides
change)ChangedEventArgs - — Emits when clear button is used
cleared - — Emits when popup closes (preventable)
close - — Component created lifecycle
created - — Component destroyed lifecycle
destroyed - — Emits when input gets focus
focus - — Emits when calendar navigates to another view
navigated - — Emits when popup opens (preventable)
open - — Emits for each day cell render (useful to disable/customize cells)
renderDayCell
- — 输入框失焦时触发
blur - — 值更改时触发(提供
change)ChangedEventArgs - — 点击清除按钮时触发
cleared - — 弹出层关闭时触发(可阻止)
close - — 组件创建生命周期事件
created - — 组件销毁生命周期事件
destroyed - — 输入框获焦时触发
focus - — 日历导航到其他视图时触发
navigated - — 弹出层打开时触发(可阻止)
open - — 每个日期单元格渲染时触发(用于禁用/自定义单元格)
renderDayCell
Common Use Cases
常见使用场景
- Birthday/Birth Date Selection: Min/Max validation, masked input, decade start view for quick year selection
- Meeting Scheduler: Date range (today + 90 days), custom working day validation, form integration
- Hotel/Flight Booking: Min/Max dates, two-way date binding, reactive forms with validation
- Application Forms: Date of birth, license expiry, appointment dates with accessibility compliance
- International Applications: Locale-aware formatting, RTL support, culture-specific calendars
- 生日选择:Min/Max验证、掩码输入、十年起始视图快速选择年份
- 会议调度:日期范围(今日+90天)、自定义工作日验证、表单集成
- 酒店/航班预订:Min/Max日期、双向日期绑定、带验证的响应式表单
- 应用表单:出生日期、许可证到期日、符合无障碍标准的预约日期
- 国际化应用:区域感知格式、RTL支持、特定区域日历
DateRangePicker
DateRangePicker
A comprehensive guide for implementing the Syncfusion Essential JS 2 DateRangePicker component in Angular applications. Learn to create date range pickers, handle range selection, manage events, and customize styling.
本指南详细介绍如何在Angular应用中实现Syncfusion Essential JS 2 DateRangePicker组件,包括创建日期范围选择器、处理范围选择、管理事件和自定义样式。
DateRangePicker Overview
DateRangePicker概述
The Syncfusion Angular DateRangePicker component is a specialized date selection widget that provides:
- Dual calendar display: Start and end date selection with synchronized calendars
- Preset ranges: Predefined options like "Last 7 Days", "This Month", "Last Month", "Custom"
- Range validation: Min/max dates, disabled ranges, required range length
- Date formatting: Customizable date format with separators and pattern support
- Event system: Created, destroyed, change, select, rangeSelected, open, close, renderDayCell events
- Keyboard shortcuts: Tab, arrow keys, enter, escape for full keyboard accessibility
- Localization support: Locale-specific formatting, day headers, month names
- Accessibility: Full WCAG 2.2 compliance, ARIA attributes, screen reader support
- Rich customization: CSS classes, custom templates, day cell rendering
- Mobile optimization: Touch-friendly interface, responsive design, full-screen mode
Package:
@syncfusion/ej2-angular-calendarsSyncfusion Angular DateRangePicker是一款专门的日期选择小部件,具备以下功能:
- 双日历显示:同步日历实现开始和结束日期选择
- 预设范围:预定义选项如“最近7天”、“本月”、“上月”、“自定义”
- 范围验证:最小/最大日期、禁用范围、必填范围长度
- 日期格式化:可自定义日期格式、分隔符和模式支持
- 事件系统:Created、destroyed、change、select、rangeSelected、open、close、renderDayCell事件
- 键盘快捷键:Tab、箭头键、回车、ESC实现完整键盘无障碍访问
- 本地化支持:特定区域的格式、日头、月份名称
- 无障碍访问:完全符合WCAG 2.2标准、ARIA属性、屏幕阅读器支持
- 丰富的自定义:CSS类、自定义模板、日期单元格渲染
- 移动端优化:触控友好界面、响应式设计、全屏模式
包依赖:
@syncfusion/ej2-angular-calendarsDocumentation Navigation
文档导航
Read the following references based on your specific needs:
根据你的需求阅读以下参考文档:
Getting Started
快速入门
📄 Read: references/getting-started.md
- Package installation and module setup
- CSS theme imports and dependencies
- Basic DateRangePicker implementation
- Component initialization in Angular
- Start and end date configuration
- Running and testing setup
📄 阅读:references/getting-started.md
- 包安装与模块配置
- CSS主题导入与依赖管理
- 基础DateRangePicker实现
- Angular中的组件初始化
- 开始和结束日期配置
- 运行与测试环境搭建
Date Range Selection
日期范围选择
📄 Read: references/date-range-selection.md
- Single click range selection
- Sequential date selection (click start, then end)
- Date range value binding (,
startDateproperties)endDate - Min/max date constraints
- Range validation and error handling
- Disabled date ranges
- Clearing selections
📄 阅读:references/date-range-selection.md
- 单击范围选择
- 顺序日期选择(先点击开始,再点击结束)
- 日期范围值绑定(、
startDate属性)endDate - 最小/最大日期约束
- 范围验证与错误处理
- 禁用日期范围
- 清除选择
Preset Ranges
预设范围
📄 Read: references/preset-ranges.md
- Predefined range options (Last 7 Days, Last Month, etc.)
- Custom preset configuration
- Programmatic preset application
- Dynamic preset generation
- Preset change events
- Combining presets with constraints
📄 阅读:references/preset-ranges.md
- 预定义范围选项(最近7天、上月等)
- 自定义预设配置
- 程序化应用预设
- 动态预设生成
- 预设更改事件
- 预设与约束结合
Events & Methods
事件与方法
📄 Read: references/events-and-methods.md
- Event handlers (change, select, rangeSelected, open, close)
- Range selection event details (startDate, endDate, daySpan)
- Programmatic methods (show(), hide(), getSelectedRange())
- Created and destroyed lifecycle events
- RenderDayCell for custom styling
- Method return types and parameters
📄 阅读:references/events-and-methods.md
- 事件处理器(change、select、rangeSelected、open、close)
- 范围选择事件详情(startDate、endDate、daySpan)
- 程序化方法(show()、hide()、getSelectedRange())
- Created和destroyed生命周期事件
- 自定义样式的RenderDayCell事件
- 方法返回类型与参数
Date Formatting & Constraints
日期格式化与约束
📄 Read: references/date-formatting-and-constraints.md
- Date format patterns and separators
- Multiple format support (format and inputFormats)
- Min/max date constraints
- Min/max days validation
- Disabled dates configuration
- Format error handling
- Locale-specific formats
📄 阅读:references/date-formatting-and-constraints.md
- 日期格式模式与分隔符
- 多格式支持(format和inputFormats)
- 最小/最大日期约束
- 最小/最大天数验证
- 禁用日期配置
- 格式错误处理
- 区域特定格式
Keyboard Navigation & Accessibility
键盘导航与无障碍访问
📄 Read: references/keyboard-navigation-and-accessibility.md
- Tab and Shift+Tab navigation
- Arrow keys for date navigation
- Enter for range selection and confirmation
- Escape to close picker
- Alt key shortcuts
- Screen reader compatibility
- ARIA labels and roles
- WCAG 2.2 AA compliance
- Focus management
📄 阅读:references/keyboard-navigation-and-accessibility.md
- Tab和Shift+Tab导航
- 箭头键日期导航
- 回车进行范围选择与确认
- ESC关闭选择器
- Alt键快捷键
- 屏幕阅读器兼容性
- ARIA标签与角色
- WCAG 2.2 AA合规性
- 焦点管理
Styling & Customization
样式与自定义
📄 Read: references/styling-and-customization.md
- CSS class customization (.e-daterangepicker, .e-calendar, .e-range-header)
- Theme selection (Material, Bootstrap, Tailwind, Fabric)
- Dark mode implementation
- Custom day cell styling via renderDayCell
- Disabled date styling
- Preset button styling
- Hover and focus states
- Responsive layout customization
📄 阅读:references/styling-and-customization.md
- CSS类自定义(.e-daterangepicker、.e-calendar、.e-range-header)
- 主题选择(Material、Bootstrap、Tailwind、Fabric)
- 深色模式实现
- 通过renderDayCell自定义日期单元格样式
- 禁用日期样式
- 预设按钮样式
- 悬停与焦点状态
- 响应式布局自定义
Globalization & Localization
全球化与本地化
📄 Read: references/globalization-and-localization.md
- Locale property for date formatting
- RTL (Right-to-Left) support for Arabic, Hebrew
- Day header formats (Short, Narrow, Abbreviated, Wide)
- Month names and day names localization
- Custom locale support
- Timezone handling
- Date format localization
📄 阅读:references/globalization-and-localization.md
- 日期格式化的locale属性
- 阿拉伯语、希伯来语的RTL(从右到左)支持
- 日头格式(Short、Narrow、Abbreviated、Wide)
- 月份和日期名称本地化
- 自定义区域支持
- 时区处理
- 日期格式本地化
API Reference
API参考
📄 Read: references/api-reference.md
- Complete property reference with descriptions
- All method signatures with return types
- Event argument types and structures
- Type interfaces (RangeEventArgs, NavigatingEventArgs, etc.)
- CSS classes and styling hooks
- Browser support matrix
📄 阅读:references/api-reference.md
- 完整属性参考及描述
- 所有方法签名及返回类型
- 事件参数类型与结构
- 类型接口(RangeEventArgs、NavigatingEventArgs等)
- CSS类与样式钩子
- 浏览器支持矩阵
Quick Start Example
快速入门示例
typescript
// app.component.ts
import { Component } from '@angular/core';
import { RangeEventArgs } from '@syncfusion/ej2-calendars';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Date range properties
startDate: Date = new Date(2026, 2, 1); // March 1, 2026
endDate: Date = new Date(2026, 2, 31); // March 31, 2026
// Constraints
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
// Range display
selectedRange: string = '';
// Event handler
onRangeChange(args: RangeEventArgs): void {
console.log('Start Date:', args.startDate);
console.log('End Date:', args.endDate);
console.log('Days in range:', args.daySpan);
this.updateRangeDisplay();
}
updateRangeDisplay(): void {
if (this.startDate && this.endDate) {
const start = this.startDate.toLocaleDateString();
const end = this.endDate.toLocaleDateString();
this.selectedRange = `${start} - ${end}`;
}
}
}html
<!-- app.component.html -->
<div style="padding: 20px; font-family: Arial, sans-serif;">
<h2>DateRangePicker Example</h2>
<div style="margin-bottom: 20px;">
<label for="dateRange">Select Date Range:</label>
<ejs-daterangepicker
id="dateRange"
placeholder="Select a date range"
[startDate]="startDate"
[endDate]="endDate"
[min]="minDate"
[max]="maxDate"
(change)="onRangeChange($event)">
</ejs-daterangepicker>
</div>
<div *ngIf="selectedRange" style="padding: 10px; background-color: #f0f0f0;">
<p><strong>Selected Range:</strong> {{ selectedRange }}</p>
</div>
</div>css
/* app.component.css */
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-inputs/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-popups/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';
:host ::ng-deep .e-daterangepicker {
margin: 10px 0;
width: 100%;
}
:host ::ng-deep .e-range-header {
background-color: #3f51b5;
color: white;
}typescript
// app.component.ts
import { Component } from '@angular/core';
import { RangeEventArgs } from '@syncfusion/ej2-calendars';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// 日期范围属性
startDate: Date = new Date(2026, 2, 1); // 2026年3月1日
endDate: Date = new Date(2026, 2, 31); // 2026年3月31日
// 约束条件
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
// 范围显示
selectedRange: string = '';
// 事件处理器
onRangeChange(args: RangeEventArgs): void {
console.log('开始日期:', args.startDate);
console.log('结束日期:', args.endDate);
console.log('范围天数:', args.daySpan);
this.updateRangeDisplay();
}
updateRangeDisplay(): void {
if (this.startDate && this.endDate) {
const start = this.startDate.toLocaleDateString();
const end = this.endDate.toLocaleDateString();
this.selectedRange = `${start} - ${end}`;
}
}
}html
<!-- app.component.html -->
<div style="padding: 20px; font-family: Arial, sans-serif;">
<h2>DateRangePicker示例</h2>
<div style="margin-bottom: 20px;">
<label for="dateRange">选择日期范围:</label>
<ejs-daterangepicker
id="dateRange"
placeholder="选择日期范围"
[startDate]="startDate"
[endDate]="endDate"
[min]="minDate"
[max]="maxDate"
(change)="onRangeChange($event)">
</ejs-daterangepicker>
</div>
<div *ngIf="selectedRange" style="padding: 10px; background-color: #f0f0f0;">
<p><strong>已选择范围:</strong> {{ selectedRange }}</p>
</div>
</div>css
/* app.component.css */
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-inputs/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-popups/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';
:host ::ng-deep .e-daterangepicker {
margin: 10px 0;
width: 100%;
}
:host ::ng-deep .e-range-header {
background-color: #3f51b5;
color: white;
}Common Patterns
常见模式
Pattern 1: Preset Date Ranges
模式1:预设日期范围
Quick selection buttons for common date ranges:
typescript
export class AppComponent {
presets: any[] = [
{ label: 'Today', start: new Date(), end: new Date() },
{ label: 'Last 7 Days', start: this.getDateDaysAgo(7), end: new Date() },
{ label: 'Last 30 Days', start: this.getDateDaysAgo(30), end: new Date() },
{ label: 'This Month', start: this.getFirstDayOfMonth(), end: new Date() },
{ label: 'Last Month', start: this.getFirstDayOfLastMonth(), end: this.getLastDayOfLastMonth() }
];
startDate: Date = new Date();
endDate: Date = new Date();
selectPreset(preset: any): void {
this.startDate = preset.start;
this.endDate = preset.end;
}
private getDateDaysAgo(days: number): Date {
const date = new Date();
date.setDate(date.getDate() - days);
return date;
}
private getFirstDayOfMonth(): Date {
return new Date(new Date().getFullYear(), new Date().getMonth(), 1);
}
private getFirstDayOfLastMonth(): Date {
const date = new Date();
return new Date(date.getFullYear(), date.getMonth() - 1, 1);
}
private getLastDayOfLastMonth(): Date {
const date = new Date();
return new Date(date.getFullYear(), date.getMonth(), 0);
}
}html
<div>
<div style="margin-bottom: 10px;">
<button *ngFor="let preset of presets"
(click)="selectPreset(preset)"
style="margin-right: 5px; padding: 8px 12px;">
{{ preset.label }}
</button>
</div>
<ejs-daterangepicker
[startDate]="startDate"
[endDate]="endDate">
</ejs-daterangepicker>
</div>快速选择常用日期范围的按钮:
typescript
export class AppComponent {
presets: any[] = [
{ label: '今日', start: new Date(), end: new Date() },
{ label: '最近7天', start: this.getDateDaysAgo(7), end: new Date() },
{ label: '最近30天', start: this.getDateDaysAgo(30), end: new Date() },
{ label: '本月', start: this.getFirstDayOfMonth(), end: new Date() },
{ label: '上月', start: this.getFirstDayOfLastMonth(), end: this.getLastDayOfLastMonth() }
];
startDate: Date = new Date();
endDate: Date = new Date();
selectPreset(preset: any): void {
this.startDate = preset.start;
this.endDate = preset.end;
}
private getDateDaysAgo(days: number): Date {
const date = new Date();
date.setDate(date.getDate() - days);
return date;
}
private getFirstDayOfMonth(): Date {
return new Date(new Date().getFullYear(), new Date().getMonth(), 1);
}
private getFirstDayOfLastMonth(): Date {
const date = new Date();
return new Date(date.getFullYear(), date.getMonth() - 1, 1);
}
private getLastDayOfLastMonth(): Date {
const date = new Date();
return new Date(date.getFullYear(), date.getMonth(), 0);
}
}html
<div>
<div style="margin-bottom: 10px;">
<button *ngFor="let preset of presets"
(click)="selectPreset(preset)"
style="margin-right: 5px; padding: 8px 12px;">
{{ preset.label }}
</button>
</div>
<ejs-daterangepicker
[startDate]="startDate"
[endDate]="endDate">
</ejs-daterangepicker>
</div>Pattern 2: Date Range Validation
模式2:日期范围验证
Validate date ranges with custom constraints:
typescript
export class AppComponent {
@ViewChild('daterangepicker') drp!: DateRangePickerComponent;
startDate: Date = new Date();
endDate: Date = new Date();
rangeError: string = '';
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
minDays: number = 1; // At least 1 day
maxDays: number = 90; // At most 90 days
onRangeChange(args: RangeEventArgs): void {
this.rangeError = '';
// Validate date range
if (args.daySpan < this.minDays) {
this.rangeError = `Range must be at least ${this.minDays} day(s)`;
return;
}
if (args.daySpan > this.maxDays) {
this.rangeError = `Range cannot exceed ${this.maxDays} days`;
return;
}
this.startDate = args.startDate;
this.endDate = args.endDate;
}
isRangeValid(): boolean {
return this.rangeError === '';
}
}使用自定义约束验证日期范围:
typescript
export class AppComponent {
@ViewChild('daterangepicker') drp!: DateRangePickerComponent;
startDate: Date = new Date();
endDate: Date = new Date();
rangeError: string = '';
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
minDays: number = 1; // 至少1天
maxDays: number = 90; // 最多90天
onRangeChange(args: RangeEventArgs): void {
this.rangeError = '';
// 验证日期范围
if (args.daySpan < this.minDays) {
this.rangeError = `范围至少为${this.minDays}天`;
return;
}
if (args.daySpan > this.maxDays) {
this.rangeError = `范围不能超过${this.maxDays}天`;
return;
}
this.startDate = args.startDate;
this.endDate = args.endDate;
}
isRangeValid(): boolean {
return this.rangeError === '';
}
}Pattern 3: Reactive Form Integration
模式3:响应式表单集成
Integrate DateRangePicker with Reactive Forms:
typescript
export class AppComponent implements OnInit {
reportForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reportForm = this.fb.group({
reportName: ['', Validators.required],
startDate: [new Date(2026, 0, 1), Validators.required],
endDate: [new Date(), Validators.required]
});
}
ngOnInit(): void {
this.reportForm.get('startDate')?.valueChanges.subscribe(date => {
console.log('Start date changed:', date);
this.validateDateRange();
});
this.reportForm.get('endDate')?.valueChanges.subscribe(date => {
console.log('End date changed:', date);
this.validateDateRange();
});
}
validateDateRange(): void {
const start = this.reportForm.get('startDate')?.value;
const end = this.reportForm.get('endDate')?.value;
if (start && end && start > end) {
this.reportForm.get('endDate')?.setErrors({ 'invalidRange': true });
} else {
this.reportForm.get('endDate')?.setErrors(null);
}
}
submitForm(): void {
if (this.reportForm.valid) {
console.log('Form values:', this.reportForm.value);
}
}
}html
<form [formGroup]="reportForm" (ngSubmit)="submitForm()">
<div>
<label>Report Name:</label>
<ejs-textbox
formControlName="reportName"
placeholder="Enter report name">
</ejs-textbox>
</div>
<div>
<label>Report Period:</label>
<ejs-daterangepicker
[formControl]="reportForm.get('startDate')"
[endDate]="reportForm.get('endDate')?.value">
</ejs-daterangepicker>
</div>
<button type="submit" [disabled]="!reportForm.valid">Generate Report</button>
</form>将DateRangePicker与响应式表单集成:
typescript
export class AppComponent implements OnInit {
reportForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reportForm = this.fb.group({
reportName: ['', Validators.required],
startDate: [new Date(2026, 0, 1), Validators.required],
endDate: [new Date(), Validators.required]
});
}
ngOnInit(): void {
this.reportForm.get('startDate')?.valueChanges.subscribe(date => {
console.log('开始日期已更改:', date);
this.validateDateRange();
});
this.reportForm.get('endDate')?.valueChanges.subscribe(date => {
console.log('结束日期已更改:', date);
this.validateDateRange();
});
}
validateDateRange(): void {
const start = this.reportForm.get('startDate')?.value;
const end = this.reportForm.get('endDate')?.value;
if (start && end && start > end) {
this.reportForm.get('endDate')?.setErrors({ 'invalidRange': true });
} else {
this.reportForm.get('endDate')?.setErrors(null);
}
}
submitForm(): void {
if (this.reportForm.valid) {
console.log('表单值:', this.reportForm.value);
}
}
}html
<form [formGroup]="reportForm" (ngSubmit)="submitForm()">
<div>
<label>报告名称:</label>
<ejs-textbox
formControlName="reportName"
placeholder="输入报告名称">
</ejs-textbox>
</div>
<div>
<label>报告周期:</label>
<ejs-daterangepicker
[formControl]="reportForm.get('startDate')"
[endDate]="reportForm.get('endDate')?.value">
</ejs-daterangepicker>
</div>
<button type="submit" [disabled]="!reportForm.valid">生成报告</button>
</form>Pattern 4: Dynamic Range Constraints
模式4:动态范围约束
Update range constraints based on business logic:
typescript
export class AppComponent {
startDate: Date = new Date();
endDate: Date = new Date();
// Dynamic constraints
minDate: Date = new Date();
maxDate: Date = new Date();
reportType: string = 'daily';
onReportTypeChange(type: string): void {
this.reportType = type;
this.updateConstraints();
}
private updateConstraints(): void {
const today = new Date();
switch (this.reportType) {
case 'daily':
// Last 7 days only
this.minDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
this.maxDate = today;
break;
case 'monthly':
// Last 12 months
this.minDate = new Date(today.getFullYear() - 1, today.getMonth(), 1);
this.maxDate = today;
break;
case 'yearly':
// Last 5 years
this.minDate = new Date(today.getFullYear() - 5, 0, 1);
this.maxDate = today;
break;
}
}
}根据业务逻辑更新范围约束:
typescript
export class AppComponent {
startDate: Date = new Date();
endDate: Date = new Date();
// 动态约束
minDate: Date = new Date();
maxDate: Date = new Date();
reportType: string = 'daily';
onReportTypeChange(type: string): void {
this.reportType = type;
this.updateConstraints();
}
private updateConstraints(): void {
const today = new Date();
switch (this.reportType) {
case 'daily':
// 仅最近7天
this.minDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
this.maxDate = today;
break;
case 'monthly':
// 最近12个月
this.minDate = new Date(today.getFullYear() - 1, today.getMonth(), 1);
this.maxDate = today;
break;
case 'yearly':
// 最近5年
this.minDate = new Date(today.getFullYear() - 5, 0, 1);
this.maxDate = today;
break;
}
}
}Pattern 5: Disabled Date Ranges
模式5:禁用日期范围
Disable specific date ranges (holidays, blackout dates):
typescript
export class AppComponent {
disabledRanges: Array<{start: Date, end: Date}> = [
{ start: new Date(2026, 11, 20), end: new Date(2026, 11, 31) }, // Christmas season
{ start: new Date(2026, 0, 1), end: new Date(2026, 0, 3) } // New Year
];
startDate: Date = new Date();
endDate: Date = new Date();
onRenderDayCell(args: RenderDayCellEventArgs): void {
// Disable dates in disabled ranges
for (const range of this.disabledRanges) {
if (args.date >= range.start && args.date <= range.end) {
args.isDisabled = true;
break;
}
}
}
}禁用特定日期范围(节假日、不可用日期):
typescript
export class AppComponent {
disabledRanges: Array<{start: Date, end: Date}> = [
{ start: new Date(2026, 11, 20), end: new Date(2026, 11, 31) }, // 圣诞季
{ start: new Date(2026, 0, 1), end: new Date(2026, 0, 3) } // 新年
];
startDate: Date = new Date();
endDate: Date = new Date();
onRenderDayCell(args: RenderDayCellEventArgs): void {
// 禁用禁用范围内的日期
for (const range of this.disabledRanges) {
if (args.date >= range.start && args.date <= range.end) {
args.isDisabled = true;
break;
}
}
}
}Key Props Reference
关键属性参考
| Prop | Type | Description | Example |
|---|---|---|---|
| | Start date of the range | |
| | End date of the range | |
| | Selected date range (array or object) | |
| | Minimum selectable date | |
| | Maximum selectable date | |
| | Minimum days in range | |
| | Maximum days in range | |
| | Date display format | |
| | Range separator character | |
| | Placeholder text | |
| | Predefined range options | |
| | Strict date validation | |
| | Read-only input field | |
| | Enable/disable component | |
| | Culture/language code | |
| | Enable RTL layout | |
| | Custom CSS classes | |
| | Component width | |
| | Allow manual text input | |
| | Open picker on input focus | |
| | Show clear button | |
| | Calendar view depth | |
| 属性 | 类型 | 描述 | 示例 |
|---|---|---|---|
| | 范围的开始日期 | |
| | 范围的结束日期 | |
| | 选中的日期范围(数组或对象) | |
| | 最小可选日期 | |
| | 最大可选日期 | |
| | 范围最小天数 | |
| | 范围最大天数 | |
| | 日期显示格式 | |
| | 范围分隔符 | |
| | 占位符文本 | |
| | 预定义范围选项 | |
| | 严格日期验证 | |
| | 只读输入框 | |
| | 启用/禁用组件 | |
| | 区域/语言代码 | |
| | 启用RTL布局 | |
| | 自定义CSS类 | |
| | 组件宽度 | |
| | 允许手动文本输入 | |
| | 输入框获焦时打开选择器 | |
| | 显示清除按钮 | |
| | 日历视图深度 | |
Common Use Cases
常见使用场景
Use Case 1: Report Date Range Selection
- User selects date range for report generation
- Apply min/max date constraints
- Support preset ranges (Last 7 Days, Last Month, etc.)
- Solution: Combine startDate/endDate with presets and min/max constraints
- Reference: Preset Ranges + Date Formatting & Constraints
Use Case 2: Booking System Range
- Select check-in and check-out dates for booking
- Disable past dates and blackout dates
- Show day count in range
- Solution: Use min date constraint, renderDayCell for disabled ranges, calculate daySpan
- Reference: Date Range Selection + Events & Methods
Use Case 3: Analytics Date Filter
- Select date range for analytics dashboard
- Multiple preset options for quick selection
- Responsive mobile-friendly interface
- Solution: Use presets with responsive styling and touch optimization
- Reference: Preset Ranges + Styling & Customization
Use Case 4: Accessible Form Field
- DateRangePicker integrated in form with full keyboard accessibility
- Screen reader compatible, WCAG 2.2 compliant
- Solution: Use with Reactive Forms, proper ARIA labels
- Reference: Keyboard Navigation & Accessibility
Use Case 5: International Date Picker
- Support multiple languages and date formats
- Show RTL for Arabic, Hebrew
- Locale-specific formatting
- Solution: Use locale property and format customization
- Reference: Globalization & Localization
场景1:报告日期范围选择
- 用户选择报告生成的日期范围
- 应用最小/最大日期约束
- 支持预设范围(最近7天、上月等)
- 解决方案:结合startDate/endDate、预设和min/max约束
- 参考文档:预设范围 + 日期格式化与约束
场景2:预订系统范围选择
- 选择入住和退房日期
- 禁用过去日期和不可用日期
- 显示范围天数
- 解决方案:使用min日期约束、renderDayCell禁用范围、计算daySpan
- 参考文档:日期范围选择 + 事件与方法
场景3:分析日期筛选
- 为分析仪表板选择日期范围
- 多个预设选项快速选择
- 响应式移动端友好界面
- 解决方案:使用预设、响应式样式和触控优化
- 参考文档:预设范围 + 样式与自定义
场景4:无障碍表单字段
- DateRangePicker集成到表单中,支持完整键盘无障碍访问
- 兼容屏幕阅读器,符合WCAG 2.2标准
- 解决方案:结合响应式表单、正确的ARIA标签
- 参考文档:键盘导航与无障碍访问
场景5:国际化日期选择器
- 支持多种语言和日期格式
- 为阿拉伯语、希伯来语显示RTL布局
- 区域特定格式
- 解决方案:使用locale属性和格式自定义
- 参考文档:全球化与本地化
DatetimePicker
DatetimePicker
A comprehensive guide for implementing the Syncfusion Essential JS 2 DatetimePicker component in Angular applications. Learn to create date and time selection interfaces, manage calendars and time pickers, handle events, and customize styling.
本指南详细介绍如何在Angular应用中实现Syncfusion Essential JS 2 DatetimePicker组件,包括创建日期和时间选择界面、管理日历和时间选择器、处理事件和自定义样式。
DatetimePicker Overview
DatetimePicker概述
The Syncfusion Angular DatetimePicker component is a combined date and time selection widget that provides:
- Integrated Date & Time Selection: Calendar popup for dates + time picker dropdown for time selection
- Flexible Formatting: Custom date formats, time formats, and locale-aware formatting
- Calendar Views: Month (default), Year, and Decade views with smooth navigation
- Time Intervals: Configurable step intervals (15, 30, 60 minutes, etc.) for time selection
- Range Constraints: Min/max dates and min/max time with strict validation
- Comprehensive Event System: change, focus, blur, open, close, created, destroyed, navigated, renderDayCell events
- Masked Input Support: Optional masked input format for guided user entry
- Persistence & RTL: State persistence across reloads and right-to-left language support
- Advanced Features: Strict mode validation, floating labels, keyboard customization, timezone support
- Accessibility: Full WCAG 2.2 compliance, keyboard navigation, WAI-ARIA support
- Theme Support: Material, Bootstrap, Tailwind, Fabric with light/dark variants
- Mobile Optimized: Full screen mode on mobile devices, touch-friendly interface
Package:
@syncfusion/ej2-angular-datetimepickersSyncfusion Angular DatetimePicker是一款结合日期和时间选择的小部件,具备以下功能:
- 集成日期与时间选择:日历弹出层选择日期 + 时间选择器下拉菜单选择时间
- 灵活格式化:自定义日期格式、时间格式和区域感知格式
- 日历视图:默认月视图,以及年视图、十年视图,支持流畅导航
- 时间间隔:可配置时间步长(15、30、60分钟等)
- 范围约束:最小/最大日期和最小/最大时间,支持严格验证
- 完善的事件系统:change、focus、blur、open、close、created、destroyed、navigated、renderDayCell事件
- 掩码输入支持:可选掩码输入格式引导用户输入
- 持久化与RTL:跨重载保留状态、从右到左语言支持
- 高级功能:严格模式验证、浮动标签、键盘自定义、时区支持
- 无障碍访问:完全符合WCAG 2.2标准、键盘导航、WAI-ARIA支持
- 主题支持:Material、Bootstrap、Tailwind、Fabric,支持明暗变体
- 移动端优化:移动设备全屏模式、触控友好界面
包依赖:
@syncfusion/ej2-angular-datetimepickersDocumentation Navigation
文档导航
Read the following references based on your specific needs:
根据你的需求阅读以下参考文档:
Getting Started
快速入门
📄 Read: references/getting-started.md
- Package installation via npm and ng add
- NgModule vs Standalone component setup
- CSS theme imports and dependencies
- Basic datetimepicker implementation
- Component initialization and running the application
- Development server setup
📄 阅读:references/getting-started.md
- 通过npm和ng add安装包
- NgModule与独立组件设置
- CSS主题导入与依赖管理
- 基础datetimepicker实现
- 组件初始化与运行应用
- 开发服务器设置
Basic Implementation
基础实现
📄 Read: references/basic-implementation.md
- Simple datetime picker with ngModel
- Two-way data binding patterns
- Readonly and disabled states
- Basic validation and constraints
- Event handling fundamentals
- ViewChild component access
📄 阅读:references/basic-implementation.md
- 使用ngModel的简单日期时间选择器
- 双向数据绑定模式
- 只读和禁用状态
- 基础验证与约束
- 事件处理基础
- ViewChild组件访问
Date & Time Configuration
日期与时间配置
📄 Read: references/date-time-configuration.md
- Date format customization (format property)
- Time format configuration (timeFormat property)
- ISO date string handling
- Date range constraints (min/max dates)
- Time range constraints (minTime/maxTime)
- Parsing multiple input formats (inputFormats)
📄 阅读:references/date-time-configuration.md
- 日期格式自定义(format属性)
- 时间格式配置(timeFormat属性)
- ISO日期字符串处理
- 日期范围约束(min/max日期)
- 时间范围约束(minTime/maxTime)
- 解析多种输入格式(inputFormats)
Calendar & Time Views
日历与时间视图
📄 Read: references/calendar-and-time-views.md
- Calendar view modes (month, year, decade)
- Start and depth properties for view control
- Time picker popup configuration
- Time step intervals and granularity
- ScrollTo position for time scrolling
- Today button and clear button behavior
📄 阅读:references/calendar-and-time-views.md
- 日历视图模式(月、年、十年)
- 视图控制的start和depth属性
- 时间选择器弹出层配置
- 时间步长与粒度
- 时间滚动的ScrollTo位置
- 今日按钮和清除按钮行为
Events & Callbacks
事件与回调
📄 Read: references/events-and-callbacks.md
- Change event with ChangedEventArgs
- Focus/blur event handling
- Open/close popup events
- Created/destroyed lifecycle events
- Navigate event for calendar navigation
- RenderDayCell for custom day styling
- Cleared event when clear button is used
📄 阅读:references/events-and-callbacks.md
- 带ChangedEventArgs的Change事件
- Focus/blur事件处理
- 弹出层打开/关闭事件
- Created/destroyed生命周期事件
- 日历导航的Navigate事件
- 自定义日期单元格样式的RenderDayCell事件
- 点击清除按钮的Cleared事件
Methods & Imperative Access
方法与命令式访问
📄 Read: references/methods-and-imperative-access.md
- ViewChild access and component references
- currentView() to get active calendar view
- navigateTo() for programmatic navigation
- focusIn/focusOut for focus management
- destroy() for cleanup and resource release
- getPersistData() for state persistence
📄 阅读:references/methods-and-imperative-access.md
- ViewChild访问与组件引用
- 获取当前日历视图的currentView()
- 程序化导航的navigateTo()
- 焦点管理的focusIn/focusOut
- 清理资源的destroy()
- 状态持久化的getPersistData()
Advanced Features
高级功能
📄 Read: references/advanced-features.md
- Masked input mode with mask placeholders
- State persistence across page reloads
- RTL (Right-to-Left) language support
- Floating label types and behavior
- Strict mode validation and error states
- Keyboard shortcuts and key configuration
- Timezone offset handling
- Full screen mode for mobile devices
- Clear button visibility and behavior
📄 阅读:references/advanced-features.md
- 带掩码占位符的掩码输入模式
- 跨页面重载的状态持久化
- RTL(从右到左)语言支持
- 浮动标签类型与行为
- 严格模式验证与错误状态
- 键盘快捷键与按键配置
- 时区偏移处理
- 移动设备全屏模式
- 清除按钮可见性与行为
Styling & Customization
样式与自定义
📄 Read: references/styling-and-customization.md
- CSS class customization (cssClass property)
- Theme selection and switching
- Dark mode implementation
- Component width and z-index configuration
- HTML attribute injection (htmlAttributes)
- Calendar mode selection (Gregorian vs Islamic)
- Day header format options
- Disabled dates and styling states
📄 阅读:references/styling-and-customization.md
- CSS类自定义(cssClass属性)
- 主题选择与切换
- 深色模式实现
- 组件宽度与z-index配置
- HTML属性注入(htmlAttributes)
- 日历模式选择(Gregorian vs Islamic)
- 日头格式选项
- 禁用日期与样式状态
Accessibility & Globalization
无障碍访问与全球化
📄 Read: references/accessibility-and-globalization.md
- WCAG 2.2 and Section 508 compliance standards
- WAI-ARIA attributes and roles
- Keyboard navigation (arrows, enter, space, escape)
- Screen reader compatibility and announcements
- Localization and locale property usage
- Day header format variations
- First day of week customization
- Week numbers and week rules
- RTL text direction support
📄 阅读:references/accessibility-and-globalization.md
- WCAG 2.2和Section 508合规标准
- WAI-ARIA属性与角色
- 键盘导航(箭头、回车、空格、ESC)
- 屏幕阅读器兼容性与播报
- 本地化与locale属性使用
- 日头格式变体
- 一周起始日自定义
- 周数与周规则
- RTL文本方向支持
API Reference
API参考
📄 Read: references/api-reference.md
- Complete property reference with types and defaults
- All method signatures with parameters and return types
- All events with event argument types
- Property descriptions and use cases
- Method examples and common patterns
- Type interfaces and enums
- Key configuration for keyboard shortcuts
- Comprehensive property-by-property guide
📄 阅读:references/api-reference.md
- 完整属性参考,含类型与默认值
- 所有方法签名,含参数与返回类型
- 所有事件,含事件参数类型
- 属性描述与使用场景
- 方法示例与常见模式
- 类型接口与枚举
- 键盘快捷键的按键配置
- 完整的逐属性指南
Quick Start Example
快速入门示例
typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangedEventArgs } from '@syncfusion/ej2-datetimepickers';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Simple datetime value
dateTimeValue: Date = new Date();
// Configuration
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
dateFormat: string = 'dd/MM/yyyy hh:mm a';
timeFormat: string = 'hh:mm a';
// Event handler
onDateTimeChange(args: ChangedEventArgs): void {
console.log('Selected DateTime:', args.value);
console.log('Event Type:', args.type);
}
onPopupOpen(): void {
console.log('Popup opened');
}
onPopupClose(): void {
console.log('Popup closed');
}
}html
<!-- app.component.html -->
<div style="padding: 20px;">
<h2>Select Date & Time</h2>
<ejs-datetimepicker
id="datetimepicker"
[value]="dateTimeValue"
[format]="dateFormat"
[timeFormat]="timeFormat"
[min]="minDate"
[max]="maxDate"
placeholder="Select date and time"
(change)="onDateTimeChange($event)"
(open)="onPopupOpen()"
(close)="onPopupClose()">
</ejs-datetimepicker>
<p *ngIf="dateTimeValue">
Selected: {{ dateTimeValue | date:'medium' }}
</p>
</div>typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangedEventArgs } from '@syncfusion/ej2-datetimepickers';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// 简单日期时间值
dateTimeValue: Date = new Date();
// 配置
minDate: Date = new Date(2020, 0, 1);
maxDate: Date = new Date(2030, 11, 31);
dateFormat: string = 'dd/MM/yyyy hh:mm a';
timeFormat: string = 'hh:mm a';
// 事件处理器
onDateTimeChange(args: ChangedEventArgs): void {
console.log('选中的日期时间:', args.value);
console.log('事件类型:', args.type);
}
onPopupOpen(): void {
console.log('弹出层已打开');
}
onPopupClose(): void {
console.log('弹出层已关闭');
}
}html
<!-- app.component.html -->
<div style="padding: 20px;">
<h2>选择日期与时间</h2>
<ejs-datetimepicker
id="datetimepicker"
[value]="dateTimeValue"
[format]="dateFormat"
[timeFormat]="timeFormat"
[min]="minDate"
[max]="maxDate"
placeholder="选择日期和时间"
(change)="onDateTimeChange($event)"
(open)="onPopupOpen()"
(close)="onPopupClose()">
</ejs-datetimepicker>
<p *ngIf="dateTimeValue">
已选择: {{ dateTimeValue | date:'medium' }}
</p>
</div>Common Patterns
常见模式
Pattern 1: Datetime Range Selection
模式1:日期时间范围选择
Select a start and end datetime for appointments, bookings, or events:
typescript
export class AppComponent {
startDateTime: Date = new Date();
endDateTime: Date = new Date(Date.now() + 3600000); // +1 hour
onStartChange(args: ChangedEventArgs): void {
// Ensure end is after start
if (this.endDateTime <= args.value) {
this.endDateTime = new Date((args.value as Date).getTime() + 3600000);
}
}
}为预约、预订或活动选择开始和结束日期时间:
typescript
export class AppComponent {
startDateTime: Date = new Date();
endDateTime: Date = new Date(Date.now() + 3600000); // +1小时
onStartChange(args: ChangedEventArgs): void {
// 确保结束时间晚于开始时间
if (this.endDateTime <= args.value) {
this.endDateTime = new Date((args.value as Date).getTime() + 3600000);
}
}
}Pattern 2: Business Hours Only
模式2:仅工作时间
Restrict time selection to business hours (9 AM - 5 PM):
typescript
export class AppComponent {
minTime: Date = new Date(2026, 2, 24, 9, 0); // 9:00 AM
maxTime: Date = new Date(2026, 2, 24, 17, 0); // 5:00 PM
datetimeValue: Date = new Date(2026, 2, 24, 10, 0);
}html
<ejs-datetimepicker
[value]="datetimeValue"
[minTime]="minTime"
[maxTime]="maxTime"
timeFormat="hh:mm a">
</ejs-datetimepicker>限制时间选择为工作时间(上午9点 - 下午5点):
typescript
export class AppComponent {
minTime: Date = new Date(2026, 2, 24, 9, 0); // 上午9:00
maxTime: Date = new Date(2026, 2, 24, 17, 0); // 下午5:00
datetimeValue: Date = new Date(2026, 2, 24, 10, 0);
}html
<ejs-datetimepicker
[value]="datetimeValue"
[minTime]="minTime"
[maxTime]="maxTime"
timeFormat="hh:mm a">
</ejs-datetimepicker>Pattern 3: Masked Input for Guided Entry
模式3:掩码输入引导
Use masked input to guide users through the datetime format:
typescript
export class AppComponent {
datetimeValue: Date;
maskPlaceholder = {
day: 'dd',
month: 'mm',
year: 'yyyy',
hour: 'hh',
minute: 'mm',
second: 'ss'
};
}html
<ejs-datetimepicker
[value]="datetimeValue"
[enableMask]="true"
[maskPlaceholder]="maskPlaceholder"
format="dd/MM/yyyy hh:mm:ss">
</ejs-datetimepicker>使用掩码输入引导用户按照日期时间格式输入:
typescript
export class AppComponent {
datetimeValue: Date;
maskPlaceholder = {
day: 'dd',
month: 'mm',
year: 'yyyy',
hour: 'hh',
minute: 'mm',
second: 'ss'
};
}html
<ejs-datetimepicker
[value]="datetimeValue"
[enableMask]="true"
[maskPlaceholder]="maskPlaceholder"
format="dd/MM/yyyy hh:mm:ss">
</ejs-datetimepicker>Pattern 4: Reactive Forms Integration
模式4:响应式表单集成
Integrate datetimepicker with Angular Reactive Forms:
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class AppComponent {
appointmentForm: FormGroup;
constructor(private fb: FormBuilder) {
this.appointmentForm = this.fb.group({
appointmentDateTime: [
new Date(),
[Validators.required]
]
});
}
submitForm(): void {
if (this.appointmentForm.valid) {
console.log(this.appointmentForm.value);
}
}
}html
<form [formGroup]="appointmentForm">
<ejs-datetimepicker
formControlName="appointmentDateTime"
format="dd/MM/yyyy hh:mm a">
</ejs-datetimepicker>
<button (click)="submitForm()" [disabled]="!appointmentForm.valid">
Submit
</button>
</form>将datetimepicker与Angular响应式表单集成:
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class AppComponent {
appointmentForm: FormGroup;
constructor(private fb: FormBuilder) {
this.appointmentForm = this.fb.group({
appointmentDateTime: [
new Date(),
[Validators.required]
]
});
}
submitForm(): void {
if (this.appointmentForm.valid) {
console.log(this.appointmentForm.value);
}
}
}html
<form [formGroup]="appointmentForm">
<ejs-datetimepicker
formControlName="appointmentDateTime"
format="dd/MM/yyyy hh:mm a">
</ejs-datetimepicker>
<button (click)="submitForm()" [disabled]="!appointmentForm.valid">
提交
</button>
</form>Pattern 5: Disabled Dates
模式5:禁用日期
Disable weekends and specific dates:
typescript
export class AppComponent {
datetimeValue: Date;
onRenderDayCell(args: RenderDayCellEventArgs): void {
// Disable weekends (0 = Sunday, 6 = Saturday)
if ((args.date as Date).getDay() === 0 || (args.date as Date).getDay() === 6) {
args.isDisabled = true;
}
// Disable specific dates
const disabledDates = [5, 15, 25]; // 5th, 15th, 25th of each month
if (disabledDates.includes((args.date as Date).getDate())) {
args.isDisabled = true;
}
}
}html
<ejs-datetimepicker
[value]="datetimeValue"
(renderDayCell)="onRenderDayCell($event)">
</ejs-datetimepicker>禁用周末和特定日期:
typescript
export class AppComponent {
datetimeValue: Date;
onRenderDayCell(args: RenderDayCellEventArgs): void {
// 禁用周末(0 = 周日,6 = 周六)
if ((args.date as Date).getDay() === 0 || (args.date as Date).getDay() === 6) {
args.isDisabled = true;
}
// 禁用特定日期
const disabledDates = [5, 15, 25]; // 每月5日、15日、25日
if (disabledDates.includes((args.date as Date).getDate())) {
args.isDisabled = true;
}
}
}html
<ejs-datetimepicker
[value]="datetimeValue"
(renderDayCell)="onRenderDayCell($event)">
</ejs-datetimepicker>Key Properties Reference
关键属性参考
| Property | Type | Purpose |
|---|---|---|
| Date | Selected datetime value for two-way binding |
| string | Date display format (e.g., 'dd/MM/yyyy hh:mm a') |
| string | Time display format in popup (e.g., 'hh:mm a') |
| Date | Minimum selectable date |
| Date | Maximum selectable date |
| Date | Minimum selectable time |
| Date | Maximum selectable time |
| number | Time interval in minutes (15, 30, 60) |
| boolean | Enable/disable the component |
| boolean | Make input readonly (select from popup only) |
| string | Placeholder text in input |
| boolean | Enable masked input mode |
| boolean | Enforce valid values only |
| boolean | Right-to-left language support |
| boolean | Persist value across page reloads |
| CalendarView | Initial calendar view (Month/Year/Decade) |
| CalendarView | Maximum calendar view level |
| string | Locale for formatting (e.g., 'en-US', 'de-DE') |
| 属性 | 类型 | 用途 |
|---|---|---|
| Date | 双向绑定的选中日期时间值 |
| string | 日期显示格式(如'dd/MM/yyyy hh:mm a') |
| string | 弹出层中的时间显示格式(如'hh:mm a') |
| Date | 最小可选日期 |
| Date | 最大可选日期 |
| Date | 最小可选时间 |
| Date | 最大可选时间 |
| number | 时间间隔(分钟,如15、30、60) |
| boolean | 启用/禁用组件 |
| boolean | 设置为只读(仅可从弹出层选择) |
| string | 输入框占位符文本 |
| boolean | 启用掩码输入模式 |
| boolean | 仅允许有效值 |
| boolean | 从右到左语言支持 |
| boolean | 跨页面重载保留值 |
| CalendarView | 初始日历视图(Month/Year/Decade) |
| CalendarView | 最大日历视图层级 |
| string | 格式化区域(如'en-US'、'de-DE') |
Common Use Cases
常见使用场景
Appointment Booking System
预约预订系统
- Use date range selection with business hours time constraints
- Display available time slots based on min/max time
- Handle form validation with required validators
- Show selected datetime confirmation
- 使用日期范围选择和工作时间约束
- 根据min/max时间显示可用时段
- 结合必填验证器处理表单验证
- 显示选中日期时间确认信息
Event Scheduling
活动调度
- Select start and end datetimes for events
- Disable weekend dates with renderDayCell
- Use step intervals for common durations (30, 60 min)
- Format output for API submission
- 选择活动的开始和结束日期时间
- 使用renderDayCell禁用周末日期
- 为常见时长使用时间步长(30、60分钟)
- 格式化输出用于API提交
Shift Management
班次管理
- Select shift start and end times
- Apply shift time constraints (min/max time)
- Handle date transitions (shifts spanning midnight)
- Support multiple timezone offsets
- 选择班次的开始和结束时间
- 应用班次时间约束(min/max时间)
- 处理跨午夜的班次过渡
- 支持多时区偏移
Billing & Invoicing
账单与发票
- Select invoice date and time
- Restrict to past dates only
- Display in user's locale format
- Export with ISO format
- 选择发票日期和时间
- 仅允许选择过去日期
- 按用户区域格式显示
- 以ISO格式导出
Next Steps
下一步
- Start with Getting Started → Install and configure the component
- Build Basic Implementation → Create simple datetime pickers
- Add Event Handling → Respond to user interactions
- Implement Advanced Features → Add masked input, persistence, RTL
- Customize Appearance → Apply themes and custom styles
- Ensure Accessibility → Support keyboard and screen readers
- Reference API → Consult complete API documentation as needed
- 从快速入门开始 → 安装并配置组件
- 构建基础实现 → 创建简单日期时间选择器
- 添加事件处理 → 响应用户交互
- 实现高级功能 → 添加掩码输入、持久化、RTL
- 自定义外观 → 应用主题和自定义样式
- 确保无障碍访问 → 支持键盘和屏幕阅读器
- 参考API → 必要时查阅完整API文档
TimePicker
TimePicker
A comprehensive guide for implementing the Syncfusion Essential JS 2 TimePicker component in Angular applications. Learn to create time selection interfaces, manage time inputs, handle events, and customize styling.
本指南详细介绍如何在Angular应用中实现Syncfusion Essential JS 2 TimePicker组件,包括创建时间选择界面、管理时间输入、处理事件和自定义样式。
TimePicker Overview
TimePicker概述
The Syncfusion Angular TimePicker component is a dedicated time selection widget that provides:
- Time Selection: Popup list with configurable time intervals for selection
- Flexible Formatting: Custom time formats, skeleton options, and locale-aware formatting
- Time Intervals: Configurable step intervals (15, 30, 60 minutes, etc.) for time selection
- Range Constraints: Min/max time with strict validation and boundary enforcement
- Comprehensive Event System: change, focus, blur, open, close, created, destroyed, cleared, itemRender events
- Masked Input Support: Optional masked input format for guided user entry
- Persistence & RTL: State persistence across reloads and right-to-left language support
- Advanced Features: Strict mode validation, floating labels, keyboard customization, timezone support
- Accessibility: Full WCAG 2.2 compliance, keyboard navigation, WAI-ARIA support
- Theme Support: Material, Bootstrap, Tailwind, Fabric with light/dark variants
- Mobile Optimized: Full screen mode on mobile devices, touch-friendly interface
Package:
@syncfusion/ej2-angular-calendarsSyncfusion Angular TimePicker是一款专门的时间选择小部件,具备以下功能:
- 时间选择:可配置时间间隔的弹出列表选择
- 灵活格式化:自定义时间格式、骨架选项和区域感知格式
- 时间间隔:可配置时间步长(15、30、60分钟等)
- 范围约束:最小/最大时间,支持严格验证和边界强制
- 完善的事件系统:change、focus、blur、open、close、created、destroyed、cleared、itemRender事件
- 掩码输入支持:可选掩码输入格式引导用户输入
- 持久化与RTL:跨重载保留状态、从右到左语言支持
- 高级功能:严格模式验证、浮动标签、键盘自定义、时区支持
- 无障碍访问:完全符合WCAG 2.2标准、键盘导航、WAI-ARIA支持
- 主题支持:Material、Bootstrap、Tailwind、Fabric,支持明暗变体
- 移动端优化:移动设备全屏模式、触控友好界面
包依赖:
@syncfusion/ej2-angular-calendarsDocumentation Navigation
文档导航
Read the following references based on your specific needs:
根据你的需求阅读以下参考文档:
Getting Started
快速入门
📄 Read: references/getting-started.md
- Package installation via npm and ng add
- NgModule vs Standalone component setup
- CSS theme imports and dependencies
- Basic timepicker implementation
- Component initialization and running the application
- Development server setup
📄 阅读:references/getting-started.md
- 通过npm和ng add安装包
- NgModule与独立组件设置
- CSS主题导入与依赖管理
- 基础timepicker实现
- 组件初始化与运行应用
- 开发服务器设置
Basic Implementation
基础实现
📄 Read: references/basic-implementation.md
- Simple time picker with ngModel
- Two-way data binding patterns
- Readonly and disabled states
- Basic validation and constraints
- Event handling fundamentals
- ViewChild component access
📄 阅读:references/basic-implementation.md
- 使用ngModel的简单时间选择器
- 双向数据绑定模式
- 只读和禁用状态
- 基础验证与约束
- 事件处理基础
- ViewChild组件访问
Time Configuration
时间配置
📄 Read: references/time-configuration.md
- Time format customization (format property)
- TimeFormatObject and skeleton options
- Step intervals and time granularity
- Min/max time constraints
- ScrollTo position for time scrolling
- Popup list configuration
📄 阅读:references/time-configuration.md
- 时间格式自定义(format属性)
- TimeFormatObject和骨架选项
- 时间步长与粒度
- 最小/最大时间约束
- 时间滚动的ScrollTo位置
- 弹出列表配置
Events & Callbacks
事件与回调
📄 Read: references/events-and-callbacks.md
- Change event with ChangeEventArgs
- Focus/blur event handling
- Open/close popup events
- Created/destroyed lifecycle events
- Cleared event when clear button is used
- ItemRender for custom time formatting
📄 阅读:references/events-and-callbacks.md
- 带ChangeEventArgs的Change事件
- Focus/blur事件处理
- 弹出层打开/关闭事件
- Created/destroyed生命周期事件
- 点击清除按钮的Cleared事件
- 自定义时间格式化的ItemRender事件
Methods & Imperative Access
方法与命令式访问
📄 Read: references/methods-and-imperative-access.md
- ViewChild access and component references
- show() to open the time popup
- hide() to close the time popup
- focusIn/focusOut for focus management
- getPersistData() for state persistence
📄 阅读:references/methods-and-imperative-access.md
- ViewChild访问与组件引用
- 打开时间弹出层的show()
- 关闭时间弹出层的hide()
- 焦点管理的focusIn/focusOut
- 状态持久化的getPersistData()
Advanced Features
高级功能
📄 Read: references/advanced-features.md
- Masked input mode with mask placeholders
- State persistence across page reloads
- RTL (Right-to-Left) language support
- Floating label types and behavior
- Strict mode validation and error states
- Keyboard shortcuts and key configuration
- Timezone offset handling
- Full screen mode for mobile devices
- Clear button visibility and behavior
- OpenOnFocus popup trigger
📄 阅读:references/advanced-features.md
- 带掩码占位符的掩码输入模式
- 跨页面重载的状态持久化
- RTL(从右到左)语言支持
- 浮动标签类型与行为
- 严格模式验证与错误状态
- 键盘快捷键与按键配置
- 时区偏移处理
- 移动设备全屏模式
- 清除按钮可见性与行为
- 输入框获焦时打开弹出层的OpenOnFocus
Styling & Customization
样式与自定义
📄 Read: references/styling-and-customization.md
- CSS class customization (cssClass property)
- Theme selection and switching
- Dark mode implementation
- Component width and z-index configuration
- HTML attribute injection (htmlAttributes)
- Placeholder and enabled state styling
- Disabled date styling and appearance
📄 阅读:references/styling-and-customization.md
- CSS类自定义(cssClass属性)
- 主题选择与切换
- 深色模式实现
- 组件宽度与z-index配置
- HTML属性注入(htmlAttributes)
- 占位符和启用状态样式
- 禁用日期样式与外观
Accessibility & Globalization
无障碍访问与全球化
📄 Read: references/accessibility-and-globalization.md
- WCAG 2.2 and Section 508 compliance standards
- WAI-ARIA attributes and roles
- Keyboard navigation (arrows, enter, space, escape)
- Screen reader compatibility and announcements
- Localization and locale property usage
- Time format variations
- RTL text direction support
📄 阅读:references/accessibility-and-globalization.md
- WCAG 2.2和Section 508合规标准
- WAI-ARIA属性与角色
- 键盘导航(箭头、回车、空格、ESC)
- 屏幕阅读器兼容性与播报
- 本地化与locale属性使用
- 时间格式变体
- RTL文本方向支持
API Reference
API参考
📄 Read: references/api-reference.md
- Complete property reference with types and defaults
- All method signatures with parameters and return types
- All events with event argument types
- Property descriptions and use cases
- Method examples and common patterns
- Type interfaces and enums
- Key configuration for keyboard shortcuts
- Comprehensive property-by-property guide
📄 阅读:references/api-reference.md
- 完整属性参考,含类型与默认值
- 所有方法签名,含参数与返回类型
- 所有事件,含事件参数类型
- 属性描述与使用场景
- 方法示例与常见模式
- 类型接口与枚举
- 键盘快捷键的按键配置
- 完整的逐属性指南
Quick Start Example
快速入门示例
typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangeEventArgs } from '@syncfusion/ej2-calendars';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Simple time value
timeValue: Date = new Date();
// Configuration
minTime: Date = new Date(2026, 2, 24, 8, 0); // 8:00 AM
maxTime: Date = new Date(2026, 2, 24, 20, 0); // 8:00 PM
format: string = 'hh:mm a';
step: number = 30; // 30-minute intervals
// Event handler
onTimeChange(args: ChangeEventArgs): void {
console.log('Selected Time:', args.value);
console.log('Selected Text:', args.text);
console.log('Is User Interaction:', args.isInteracted);
}
onPopupOpen(): void {
console.log('Time popup opened');
}
onPopupClose(): void {
console.log('Time popup closed');
}
}html
<!-- app.component.html -->
<div style="padding: 20px;">
<h2>Select a Time</h2>
<ejs-timepicker
id="timepicker"
[value]="timeValue"
[format]="format"
[min]="minTime"
[max]="maxTime"
[step]="step"
placeholder="Select time"
(change)="onTimeChange($event)"
(open)="onPopupOpen()"
(close)="onPopupClose()">
</ejs-timepicker>
<p *ngIf="timeValue">
Selected Time: {{ timeValue | date:'shortTime' }}
</p>
</div>typescript
// app.component.ts
import { Component } from '@angular/core';
import { ChangeEventArgs } from '@syncfusion/ej2-calendars';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// 简单时间值
timeValue: Date = new Date();
// 配置
minTime: Date = new Date(2026, 2, 24, 8, 0); // 上午8:00
maxTime: Date = new Date(2026, 2, 24, 20, 0); // 晚上8:00
format: string = 'hh:mm a';
step: number = 30; // 30分钟间隔
// 事件处理器
onTimeChange(args: ChangeEventArgs): void {
console.log('选中的时间:', args.value);
console.log('选中的文本:', args.text);
console.log('是否用户交互:', args.isInteracted);
}
onPopupOpen(): void {
console.log('时间弹出层已打开');
}
onPopupClose(): void {
console.log('时间弹出层已关闭');
}
}html
<!-- app.component.html -->
<div style="padding: 20px;">
<h2>选择时间</h2>
<ejs-timepicker
id="timepicker"
[value]="timeValue"
[format]="format"
[min]="minTime"
[max]="maxTime"
[step]="step"
placeholder="选择时间"
(change)="onTimeChange($event)"
(open)="onPopupOpen()"
(close)="onPopupClose()">
</ejs-timepicker>
<p *ngIf="timeValue">
已选择时间: {{ timeValue | date:'shortTime' }}
</p>
</div>Common Patterns
常见模式
Pattern 1: Business Hours Time Selection
模式1:工作时间选择
Select time within business hours (9 AM - 6 PM):
typescript
export class AppComponent {
minTime: Date = new Date(2026, 2, 24, 9, 0); // 9:00 AM
maxTime: Date = new Date(2026, 2, 24, 18, 0); // 6:00 PM
timeValue: Date = new Date(2026, 2, 24, 10, 0);
format: string = 'hh:mm a';
step: number = 15; // 15-minute intervals
}html
<ejs-timepicker
[value]="timeValue"
[min]="minTime"
[max]="maxTime"
[step]="step"
[format]="format"
placeholder="Select appointment time">
</ejs-timepicker>选择工作时间内的时间(上午9点 - 下午6点):
typescript
export class AppComponent {
minTime: Date = new Date(2026, 2, 24, 9, 0); // 上午9:00
maxTime: Date = new Date(2026, 2, 24, 18, 0); // 下午6:00
timeValue: Date = new Date(2026, 2, 24, 10, 0);
format: string = 'hh:mm a';
step: number = 15; // 15分钟间隔
}html
<ejs-timepicker
[value]="timeValue"
[min]="minTime"
[max]="maxTime"
[step]="step"
[format]="format"
placeholder="选择预约时间">
</ejs-timepicker>Pattern 2: 24-Hour Format
模式2:24小时格式
Display time in 24-hour military format:
typescript
export class AppComponent {
timeValue: Date = new Date();
format: string = 'HH:mm'; // 24-hour format
step: number = 30;
}html
<ejs-timepicker
[value]="timeValue"
[format]="format"
[step]="step"
placeholder="Select time (24-hour)">
</ejs-timepicker>以24小时军事格式显示时间:
typescript
export class AppComponent {
timeValue: Date = new Date();
format: string = 'HH:mm'; // 24小时格式
step: number = 30;
}html
<ejs-timepicker
[value]="timeValue"
[format]="format"
[step]="step"
placeholder="选择时间(24小时制)">
</ejs-timepicker>Pattern 3: Masked Input for Guided Entry
模式3:掩码输入引导
Use masked input to guide users through time entry:
typescript
export class AppComponent {
timeValue: Date;
enableMask: boolean = true;
maskPlaceholder = {
hour: 'hh',
minute: 'mm',
second: 'ss'
};
format: string = 'hh:mm:ss a';
}html
<ejs-timepicker
[value]="timeValue"
[enableMask]="enableMask"
[maskPlaceholder]="maskPlaceholder"
format="hh:mm:ss a">
</ejs-timepicker>使用掩码输入引导用户输入时间:
typescript
export class AppComponent {
timeValue: Date;
enableMask: boolean = true;
maskPlaceholder = {
hour: 'hh',
minute: 'mm',
second: 'ss'
};
format: string = 'hh:mm:ss a';
}html
<ejs-timepicker
[value]="timeValue"
[enableMask]="enableMask"
[maskPlaceholder]="maskPlaceholder"
format="hh:mm:ss a">
</ejs-timepicker>Pattern 4: Reactive Forms Integration
模式4:响应式表单集成
Integrate timepicker with Angular Reactive Forms:
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class AppComponent {
appointmentForm: FormGroup;
constructor(private fb: FormBuilder) {
this.appointmentForm = this.fb.group({
appointmentTime: [
new Date(),
[Validators.required]
]
});
}
submitForm(): void {
if (this.appointmentForm.valid) {
console.log(this.appointmentForm.value);
}
}
}html
<form [formGroup]="appointmentForm">
<ejs-timepicker
formControlName="appointmentTime"
format="hh:mm a"
placeholder="Select time">
</ejs-timepicker>
<button (click)="submitForm()" [disabled]="!appointmentForm.valid">
Submit
</button>
</form>将timepicker与Angular响应式表单集成:
typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class AppComponent {
appointmentForm: FormGroup;
constructor(private fb: FormBuilder) {
this.appointmentForm = this.fb.group({
appointmentTime: [
new Date(),
[Validators.required]
]
});
}
submitForm(): void {
if (this.appointmentForm.valid) {
console.log(this.appointmentForm.value);
}
}
}html
<form [formGroup]="appointmentForm">
<ejs-timepicker
formControlName="appointmentTime"
format="hh:mm a"
placeholder="选择时间">
</ejs-timepicker>
<button (click)="submitForm()" [disabled]="!appointmentForm.valid">
提交
</button>
</form>Pattern 5: Time Range Selection
模式5:时间范围选择
Select start and end times for a duration:
typescript
export class AppComponent {
startTime: Date = new Date();
endTime: Date = new Date(Date.now() + 3600000); // +1 hour
onStartTimeChange(args: ChangeEventArgs): void {
// Ensure end time is after start time
if (args.value && this.endTime <= args.value) {
this.endTime = new Date(args.value.getTime() + 3600000); // +1 hour
}
}
}html
<div>
<label>Start Time:</label>
<ejs-timepicker
[value]="startTime"
format="hh:mm a"
(change)="onStartTimeChange($event)">
</ejs-timepicker>
<label>End Time:</label>
<ejs-timepicker
[value]="endTime"
[min]="startTime"
format="hh:mm a">
</ejs-timepicker>
</div>选择持续时间的开始和结束时间:
typescript
export class AppComponent {
startTime: Date = new Date();
endTime: Date = new Date(Date.now() + 3600000); // +1小时
onStartTimeChange(args: ChangeEventArgs): void {
// 确保结束时间晚于开始时间
if (args.value && this.endTime <= args.value) {
this.endTime = new Date(args.value.getTime() + 3600000); // +1小时
}
}
}html
<div>
<label>开始时间:</label>
<ejs-timepicker
[value]="startTime"
format="hh:mm a"
(change)="onStartTimeChange($event)">
</ejs-timepicker>
<label>结束时间:</label>
<ejs-timepicker
[value]="endTime"
[min]="startTime"
format="hh:mm a">
</ejs-timepicker>
</div>Key Properties Reference
关键属性参考
| Property | Type | Purpose |
|---|---|---|
| Date | Selected time value for two-way binding |
| string | Time display format (e.g., 'hh:mm a') |
| Date | Minimum selectable time |
| Date | Maximum selectable time |
| number | Time interval in minutes (15, 30, 60) |
| boolean | Enable/disable the component |
| boolean | Make input readonly (select from popup only) |
| string | Placeholder text in input |
| boolean | Enable masked input mode |
| boolean | Enforce valid values only |
| boolean | Right-to-left language support |
| boolean | Persist value across page reloads |
| Date | Default scroll position in time list |
| string | Locale for formatting (e.g., 'en-US', 'de-DE') |
| string | Custom CSS class for styling |
| string | Component width |
| number | Z-index for popup |
| boolean | Show/hide clear icon |
| boolean | Open popup on input focus |
| string | Floating label behavior (Never/Always/Auto) |
| 属性 | 类型 | 用途 |
|---|---|---|
| Date | 双向绑定的选中时间值 |
| string | 时间显示格式(如'hh:mm a') |
| Date | 最小可选时间 |
| Date | 最大可选时间 |
| number | 时间间隔(分钟,如15、30、60) |
| boolean | 启用/禁用组件 |
| boolean | 设置为只读(仅可从弹出层选择) |
| string | 输入框占位符文本 |
| boolean | 启用掩码输入模式 |
| boolean | 仅允许有效值 |
| boolean | 从右到左语言支持 |
| boolean | 跨页面重载保留值 |
| Date | 时间列表中的默认滚动位置 |
| string | 格式化区域(如'en-US'、'de-DE') |
| string | 自定义CSS类用于样式 |
| string | 组件宽度 |
| number | 弹出层的Z-index |
| boolean | 显示/隐藏清除图标 |
| boolean | 输入框获焦时打开弹出层 |
| string | 浮动标签行为(Never/Always/Auto) |
Common Use Cases
常见使用场景
Appointment Booking System
预约预订系统
- Select available time slots from a list
- Restrict to business hours with min/max time
- Use 15 or 30-minute step intervals
- Handle form validation with required validators
- Display selected time confirmation
- 从列表中选择可用时段
- 限制为工作时间(min/max time)
- 使用15或30分钟时间步长
- 结合必填验证器处理表单验证
- 显示选中时间确认信息
Shift Management
班次管理
- Select shift start and end times
- Apply shift time constraints
- Support multiple timezone offsets
- Handle shift transitions (spanning midnight)
- Export times in ISO format
- 选择班次的开始和结束时间
- 应用班次时间约束
- 支持多时区偏移
- 处理跨午夜的班次过渡
- 以ISO格式导出时间
Meeting Scheduling
会议调度
- Select meeting time with business hours constraint
- Use 30-minute step intervals for standard durations
- Display time in user's locale format
- Prevent double bookings with validation
- Sync with calendar component for availability
- 选择会议时间,限制为工作时间
- 使用30分钟时间步长对应标准时长
- 按用户区域格式显示时间
- 通过验证防止重复预订
- 与日历组件同步显示可用性
Time Tracking
时间跟踪
- Record clock-in and clock-out times
- Restrict to business hours
- Use masked input for quick entry
- Persist times for audit trail
- Export times for payroll integration
- 记录打卡和签退时间
- 限制为工作时间
- 使用掩码输入快速录入
- 持久化时间用于审计追踪
- 导出时间用于薪资集成
Event Registration
活动注册
- Select event attendance time slot
- Show available time ranges
- Use clear button for corrections
- Support multiple time formats
- Accessibility for assistive technologies
- 选择活动参与时段
- 显示可用时间范围
- 使用清除按钮修正选择
- 支持多种时间格式
- 为辅助技术提供无障碍访问
Next Steps
下一步
- Start with Getting Started → Install and configure the component
- Build Basic Implementation → Create simple time pickers
- Add Event Handling → Respond to user interactions
- Implement Advanced Features → Add masked input, persistence, RTL
- Customize Appearance → Apply themes and custom styles
- Ensure Accessibility → Support keyboard and screen readers
- Reference API → Consult complete API documentation as needed
- 从快速入门开始 → 安装并配置组件
- 构建基础实现 → 创建简单时间选择器
- 添加事件处理 → 响应用户交互
- 实现高级功能 → 添加掩码输入、持久化、RTL
- 自定义外观 → 应用主题和自定义样式
- 确保无障碍访问 → 支持键盘和屏幕阅读器
- 参考API → 必要时查阅完整API文档