
Angular Material Datepicker 公开 API 全解析从日历组件到日期范围选择策略【免费下载链接】componentsComponent infrastructure and Material Design components for Angular项目地址: https://gitcode.com/GitHub_Trending/co/components本文基于 Angular Material 组件库仓库中的 API 报告 goldens/material/datepicker/index.api.md由 API Extractor 自动生成与官方使用指南 src/material/datepicker/datepicker.md 整理而成系统梳理 Datepicker 模块的全部公开 API 表面日历三视图、日期选择模型、范围选择策略、输入/切换/操作按钮指令以及国际化注入令牌。读者读完后可以准确理解MatDatepicker生态中各公开类型、接口与注入令牌的职责划分并能在自己的 Angular 应用中正确引用、继承或注入这些 API。Datepicker 模块的公开 API 全景Datepicker 不是单一组件而是由「弹出面板 输入框 日历网格 选择模型」组合而成的功能家族。API 报告显示angular/material/datepicker的公开 API 覆盖了从底层日历视图到高层表单控件的完整层级类型别名type aliasDateFilterFn、DatepickerDropdownPositionX/Y、MatCalendarView、MatCalendarCellClassFunction、MatCalendarCellCssClasses、ExtractDateTypeFromSelection常量与注入令牌yearsPerPage、yearsPerRow、MAT_DATE_RANGE_SELECTION_STRATEGY、MAT_DATEPICKER_SCROLL_STRATEGY、MAT_DATEPICKER_VALIDATORS、MAT_DATEPICKER_VALUE_ACCESSOR日历视图组件MatCalendar、MatMonthView、MatYearView、MatMultiYearView、MatCalendarBody、MatCalendarHeader、MatCalendarCell日期选择模型MatDateSelectionModel抽象基类、MatSingleDateSelectionModel、MatRangeDateSelectionModel、DateRange日期选择器组件MatDatepicker、MatDateRangePicker、MatDatepickerContent、MatDatepickerInput、MatDateRangeInput、MatStartDate、MatEndDate、MatDatepickerToggle、MatDatepickerActions、MatDatepickerApply、MatDatepickerCancel国际化服务MatDatepickerIntl模块MatDatepickerModule。其中MatCalendarView是贯穿全模块的核心类型其取值决定了日历当前展示的视图层级export type MatCalendarView month | year | multi-year;与之配套的是分页常量yearsPerPage 24与yearsPerRow 4它们共同决定了多年度视图multi-year view的网格布局——每行展示 4 个年份每页共 24 个年份这与 API 报告中MatMultiYearView与MatCalendarBody的numCols、rows网格渲染逻辑一一对应。MatCalendar 内联日历三种视图与事件流MatCalendarD是一个可在页面中直接内联使用的日历组件不依赖弹出面板它同时是MatDatepickerContent内部的日历实现。从 API 报告可以看出它实现了AfterContentInit、AfterViewChecked、OnChanges、OnDestroy四个生命周期接口输入输出非常丰富。关键输入Input输入类型说明headerComponentComponentTypeany自定义日历头部组件即指南中的calendarHeaderComponentstartAtD \| null日历打开时定位的起始日期startViewMatCalendarView初始视图month/year/multi-year默认为monthselectedDateRangeD \| D \| null当前选中值兼容单选与范围选择minDate/maxDateD \| null可选日期下限/上限dateFilter(date: D) boolean单日期禁用过滤器dateClassMatCalendarCellClassFunctionD为特定日期附加 CSS 类comparisonStart/comparisonEndD \| null对比范围comparison range的起止startDateAccessibleName/endDateAccessibleNamestring \| null起止日期的无障碍名称关键输出OutputselectedChange选中值变化yearSelected/monthSelected在 multi-year 与 year 视图中选中年份/月份时发出「归一化日期」——年份会归一化为该年 1 月 1 日月份会归一化为该月 1 日例如使用原生Date时选中 2017 年会发出new Date(2017, 0, 1)viewChanged视图切换事件_userSelection/_userDragDrop内部使用的用户选择与拖拽事件下划线开头属于私有/内部 API。MatCalendar还暴露了focusActiveCell()、updateTodaysDate()等公开方法以及activeDate当前活动日期可读写和currentView当前视图可读写两个可读写属性用于程序化控制日历状态。三种视图组件的职责分工API 报告中的三个视图组件MatMonthView、MatYearView、MatMultiYearView具有高度一致的结构都注入DateAdapter、实现AfterContentInit与OnDestroy、拥有activeDate/selected/minDate/maxDate/dateFilter/dateClass输入并各自发出对应的选中事件MatMonthView发出selectedChange、_userSelection、dragStarted、dragEnded、activeDateChangeMatYearView发出selectedChange、monthSelected、activeDateChangeMatMultiYearView发出selectedChange、yearSelected、activeDateChange。三者均持有_matCalendarBody: MatCalendarBody把日期网格的实际渲染与键盘交互委托给MatCalendarBody选择器[mat-calendar-body]。MatCalendarBody内部以rows: MatCalendarCell[][]描述网格并提供_isInRange、_isRangeStart、_isRangeEnd、_isInPreview、_isComparisonStart、_isInComparisonRange等大量私有判断方法用于绘制选中、悬停预览与对比范围的高亮状态。日历单元格与 CSS 类MatCalendarCellD是网格中的单个单元格数据类字段包括value数值、displayValue显示文本、ariaLabel无障碍标签、enabled是否可选、cssClasses、compareValue对比值与rawValue原始日期值。MatCalendarHeaderD则是默认头部提供上一段/下一段导航按钮与视图切换按钮currentPeriodClicked、nextClicked、previousClicked等方法。日期高亮通过MatCalendarCellClassFunctionD实现export type MatCalendarCellClassFunctionD ( date: D, view: month | year | multi-year, ) MatCalendarCellCssClasses; export type MatCalendarCellCssClasses | string | string[] | Setstring | Recordstring, any;返回值可以是ngClass支持的任何形式例如在月份视图中把周末日期附加自定义类。使用指南在「Highlighting specific dates」一节中对此有完整示例见 datepicker.md。日期选择模型单选与范围选的内在逻辑MatDateSelectionModelS, D是模块内部的抽象选择模型公开但标注为 docs-private 用途它通过selectionChanged: ObservableDateSelectionModelChangeS对外广播变化DateSelectionModelChangeS接口包含selection新值、source触发源与可选的oldValue旧值。抽象基类定义四个抽象方法add(date: D | null)向当前选择添加一个日期isValid()当前选择是否合法isComplete()当前选择是否完整clone()克隆模型。MatSingleDateSelectionModelD的add语义是「新日期直接覆盖旧选择」isComplete()只要selection ! null即为真。MatRangeDateSelectionModelD的add语义则是经典的「两段式填充」源码见 date-selection-model.tsstart为空 → 把日期设为startstart非空且end为空 → 把日期设为end两者都已填满 → 重置新日期成为新的startend置空。其isValid()的判定同样值得注意同一文件 L174-L197空范围合法完整范围要求两端都是合法日期实例且start end部分范围要求已有的那一端合法。两个模型类都提供了工厂 providerMAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER/MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER通过useFactory在找不到父级模型时自动创建默认模型从而在MatCalendar与MatDatepickerContent之间共享同一份选择状态。DateRangeD是范围选择的载体类型start/end均为可空的只读字段且通过私有字段_disableStructuralEquivalency!: never阻止结构等价的对象被直接赋值给DateRange类型变量保证类型安全。日期范围选择策略MAT_DATE_RANGE_SELECTION_STRATEGY 与拖拽范围选择的行为逻辑被抽象为MatDateRangeSelectionStrategyD接口与渲染层解耦。该接口包含三个方法完整定义见 date-range-selection-strategy.ts方法触发时机selectionFinished(date, currentRange, event)用户完成一次点选event目前对应clickcreatePreview(activeDate, currentRange, event)用户悬停或聚焦新日期日历需展示预览范围createDrag?(dragOrigin, originalRange, newDate, event)用户拖拽已有范围的一端可选实现模块内置的默认实现是DefaultMatCalendarRangeStrategyD其点选逻辑是start为空则设置startstart已存在且end为空、新日期不早于start则补全end否则重置为「新日期为 start、end 为空」。预览逻辑是只有「已有 start、无 end、存在活动日期」时才显示从start到活动日期的预览范围。createDrag的默认实现支持拖拽范围的两端来调整范围长度同时保持范围长度不变——当拖拽起点是start时更新start若越过end则同步平移end拖拽end时对称处理date-range-selection-strategy.ts。这一整套行为通过注入令牌替换export const MAT_DATE_RANGE_SELECTION_STRATEGY: InjectionTokenMatDateRangeSelectionStrategyany;官方指南中的典型场景是自定义策略把范围限制为「恰好 5 天」。使用时先实现接口再在 providers 中提供该令牌即可bootstrapApplication(MyApp, { providers: [ {provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FiveDayRangeSelectionStrategy}, ], });日期选择器面板与表单控件MatDatepicker 与 MatDatepickerBaseMatDatepickerD继承自MatDatepickerBaseMatDatepickerControlD, D | null, D负责弹出面板本身MatDateRangePickerD则继承MatDatepickerBaseMatDateRangePickerInputD, DateRangeD, D用于范围选择。面板与输入框之间的契约由接口MatDatepickerPanelC, S, D定义export interface MatDatepickerPanelC extends MatDatepickerControlD, S, D { closedStream: EventEmittervoid; color: ThemePalette; datepickerInput: C; disabled: boolean; id: string; opened: boolean; openedStream: EventEmittervoid; registerInput(input: C): MatDateSelectionModelS, D; stateChanges: Subjectvoid; open(): void; }MatDatepickerControlD则是输入控件需要实现的接口包含dateFilter、min/max、disabled、stateChanges、getConnectedOverlayOrigin()、getStartValue()、getThemePalette()、getOverlayLabelId()等成员。这种接口化设计使得MatDatepickerToggle、MatDatepickerActions等都能面向接口编程同时兼容普通 input 与 range input。MatDatepickerInput 与表单接入MatDatepickerInputD选择器input[matDatepicker]实现了ControlValueAccessor因此可以无缝配合formControl、ngModel、formGroupName等angular/forms指令。其输入别名在 API 报告中可以查到输入别名说明matDatepickermatDatepicker绑定的日期选择器面板min/maxmin/max最小/最大可选日期同时注册验证器dateFiltermatDatepickerFilter日期过滤函数DateFilterFnDDateFilterFnD的类型定义是(date: D | null) boolean。min/max/matDatepickerFilter三种验证分别产生matDatepickerMin、matDatepickerMax、matDatepickerFilter三种错误键可直接在模板错误提示中判断。MatDatepickerInput还提供两个专有事件与原生(input)/(change)区分原生事件在日历中选择时不会触发(dateInput)用户在输入框键入或从日历选择导致值变化时触发(dateChange)用户完成键入输入框失焦或从日历选定日期时触发。MatDateRangeInput 家族MatDateRangeInputD选择器mat-date-range-input实现MatFormFieldControlDateRangeD内部要求两个子输入框input[matStartDate]与input[matEndDate]对应MatStartDateD与MatEndDateD两个指令。典型模板mat-date-range-input [rangePicker]picker input matStartDate placeholderStart date input matEndDate placeholderEnd date /mat-date-range-input mat-date-range-picker #picker/mat-date-range-picker该组件还支持separator起止日期间的分隔符、comparisonStart/comparisonEnd对比范围输入并实现了disableAutomaticLabeling、onContainerClick()、setDescribedByIds()等MatFormFieldControl契约方法可与mat-form-field的浮动标签、错误提示深度集成。配合FormGroup指令可以把起止日期作为一个整体分组校验官方示例见 date-range-picker-forms。切换按钮与操作按钮MatDatepickerToggleD选择器mat-datepicker-toggle提供打开面板的图标按钮输入for别名绑定面板、tabIndex、aria-label、disabled、disableRipple。图标内容可通过[matDatepickerToggleIcon]指令自定义对应MatDatepickerToggleIcon指令。MatDatepickerActions选择器mat-datepicker-actions, mat-date-range-picker-actions与两个指令配合实现「确认/取消」流程[matDatepickerApply]/[matDateRangePickerApply]应用当前选择并关闭[matDatepickerCancel]/[matDateRangePickerCancel]放弃选择并关闭。启用操作按钮后点击日期不再立即提交而是等用户显式点击「Apply」才把值写入数据模型这对无障碍用户尤其重要。此特性在 API 报告中体现为MatDatepickerContent的_actionsPortal与_assignActions()机制——操作按钮内容通过TemplatePortal注入到弹出面板的 actions 区域。注入令牌与国际化MAT_DATEPICKER 系令牌API 报告列出了三个与日期选择器内部机制相关的注入令牌export const MAT_DATEPICKER_SCROLL_STRATEGY: InjectionToken() ScrollStrategy; export const MAT_DATEPICKER_VALIDATORS: any; export const MAT_DATEPICKER_VALUE_ACCESSOR: any;MAT_DATEPICKER_SCROLL_STRATEGY自定义弹出面板的滚动策略返回ScrollStrategy工厂函数基于angular/cdk/overlayMAT_DATEPICKER_VALUE_ACCESSOR提供ControlValueAccessor的 multi-provider实现MatDatepickerInput与angular/forms的桥接MAT_DATEPICKER_VALIDATORS注册日期验证器的 multi-provider。这些令牌在 datepicker-input.ts 与 datepicker-base.ts 中定义并提供普通使用者一般不需要直接触碰但理解它们有助于排查表单接入问题。国际化四要素与 MatDatepickerIntl指南把日期选择器国际化拆成四个层面区域设置locale、日期实现DateAdapter、显示/解析格式MAT_DATE_FORMATS、界面文案MatDatepickerIntl。MatDatepickerIntl服务集中管理所有界面文案API 报告完整列出了其公开字段openCalendarLabel、closeCalendarLabel、nextMonthLabel、prevMonthLabel、nextYearLabel、prevYearLabel、nextMultiYearLabel、prevMultiYearLabel、switchToMonthViewLabel、switchToMultiYearViewLabel、calendarLabel、comparisonDateLabel以及两个已废弃字段startDateLabel/endDateLabel标注deprecated。此外还有formatYearRange(start, end)与formatYearRangeLabel(start, end)两个格式化方法以及changes: Subjectvoid用于广播文案变更。自定义文案只需子类化并覆盖字段bootstrapApplication(MyApp, { providers: [ {provide: MatDatepickerIntl, useClass: MyIntl}, provideNativeDateAdapter(), ], });日期实现与格式DateAdapter 与 MAT_DATE_FORMATSDatepicker 是「日期实现无关」的DateAdapterD抽象类定义了对日期类型D的全部操作比较、加减、格式化、解析等。仓库提供多种现成适配器对应源码目录见 src/material 下的 material-date-fns-adapter、material-luxon-adapter、material-moment-adapterAPI 报告中MatCalendar、MatDatepickerInput等类的泛型参数D即由所选适配器决定provideNativeDateAdapter/MatNativeDateModule日期类型Date仅完整支持 en-USprovideDateFnsAdapter/MatDateFnsModule日期类型Date依赖 date-fnsprovideLuxonDateAdapter/MatLuxonDateModule日期类型DateTime依赖 LuxonprovideMomentDateAdapter/MatMomentDateModule日期类型Moment依赖 Moment.js。所有 provider 都同时提供DateAdapter与MAT_DATE_FORMATS。若需自定义解析/显示格式可覆盖MAT_DATE_FORMATS或直接把格式对象传入 provider例如provideNativeDateAdapter(MY_NATIVE_DATE_FORMATS)也可以完全自定义子类化DateAdapter并通过{provide: DateAdapter, useClass: MyDateAdapter}提供。由于DateAdapter是泛型类在ViewChild(MatDatepicker)等场景中应携带与所选适配器对应的泛型参数ViewChild(MatDatepicker) datepicker: MatDatepickerDate;无障碍设计与键盘交互指南的 Accessibility 一节与 API 报告相互印证MatDatepicker弹出层使用roledialog交互模式内部日历实现rolegrid模式MatDatepickerInput与MatDatepickerToggle均会设置aria-haspopup属性对应 API 报告中的getOverlayLabelId()、ariaLabel等成员始终建议启用确认操作按钮matDatepickerActions让辅助技术用户显式确认选择输入框应通过mat-label、aria-label、aria-labelledby或MatDatepickerIntl提供有意义的标签并通过mat-hint等方式告知日期格式如 MM/DD/YYYYMatDatepickerToggle与MatDatepicker应同时使用——移动端屏幕阅读器用户依赖图标按钮打开面板。键盘交互方面打开/关闭面板的快捷键为AltDown Arrow与Escape月份视图内支持方向键逐日移动、Home/End跳到月初/月末、Page Up/Page Down跨月移动、AltPage Up/Page Down跨年移动、Enter选中当前日期年视图与多年视图有对应的同类操作年视图按 4 个月一行、多年视图按 4 年一行、每页 24 项——与yearsPerRow/yearsPerPage常量吻合。常见报错与排查API 报告与指南共同指向三类高频错误MatDatepicker: No provider found for DateAdapter/MAT_DATE_FORMATS应用缺少日期适配器 provider在 app config 中调用provideNativeDateAdapter()或其它适配器 provider即可解决A MatDatepicker can only be associated with a single input同一个mat-datepicker被多个input通过matDatepicker属性绑定一个面板只能关联一个输入框Attempted to open an MatDatepicker with no associated input面板未关联任何输入框需要用模板引用建立绑定input [matDatepicker]picker mat-datepicker #picker/mat-datepicker模块组织与按需引入MatDatepickerModule的 NgModule 声明与导出列表在 API 报告中完整可见它内部引入MatButtonModule、OverlayModule来自angular/cdk/overlay、A11yModule、PortalModule声明并导出了MatCalendar、MatCalendarBody、MatDatepicker、MatDatepickerContent、MatDatepickerInput、MatDatepickerToggle、MatDatepickerToggleIcon、MatMonthView、MatYearView、MatMultiYearView、MatCalendarHeader、MatDateRangeInput、MatStartDate、MatEndDate、MatDateRangePicker、MatDatepickerActions、MatDatepickerCancel、MatDatepickerApply等全部公开组件与指令同时导出BidiModule与CdkScrollableModule供消费者使用。在独立组件standalone模式下可仅导入用到的组件或MatDatepickerModule整体模块化应用则在 NgModule 的imports中声明MatDatepickerModule并在 app config 中同时提供日期适配器。提示完整的 API 报告由 API Extractor 自动生成并受版本金样golden file机制保护任何公开 API 的增删改都需要同步更新该报告它是理解模块「稳定契约」的一手资料。文中所有类型定义、令牌名与组件成员均可对照 goldens/material/datepicker/index.api.md 逐一核实更详细的用法示例与配置参数请参阅 src/material/datepicker/datepicker.md。【免费下载链接】componentsComponent infrastructure and Material Design components for Angular项目地址: https://gitcode.com/GitHub_Trending/co/components创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考