Angular Material日期范围选择器初始设[opened]="true"时异常
解决Angular Material 15.2.9中mat-date-range-picker初始展开报错问题
问题原因
Angular 15对mat-date-range-picker的初始化逻辑做了调整,直接在模板中设置[opened]="true"时,picker会在与关联的mat-date-range-input完成绑定前触发打开操作,导致picker无法找到对应的输入框实例,进而抛出Cannot read properties of undefined (reading '_getAccessibleName')错误。
解决方案
通过延迟执行picker的打开操作,确保输入框与picker完成绑定后再触发展开。具体步骤如下:
- 移除模板中的
[opened]="true"绑定 - 在组件类中通过
ViewChild获取picker实例 - 在
ngAfterViewInit钩子中延迟调用open()方法
修改后的代码示例
模板代码
<button mat-button color="primary" (click)="picker.open()"> <span>{{ apiFilter.from && apiFilter.to ? (apiFilter.from.toFormat('d. MMM yyyy')) + ' til ' + (apiFilter.to.toFormat('d. MMM yyyy')) : 'Vælg periode' }} </span> <mat-date-range-input class="date-filter-input" [rangePicker]="picker"> <input (dateChange)="onUpdateDateRange($event.value, 'from')" [value]="apiFilter.from" matStartDate /> <input (dateChange)="onUpdateDateRange($event.value, 'to')" [value]="apiFilter.to" matEndDate /> </mat-date-range-input> <mat-date-range-picker #picker></mat-date-range-picker> </button>
组件类代码
import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { MatDateRangePicker } from '@angular/material/datepicker'; @Component({ // 你的组件元数据(selector, templateUrl等) }) export class YourComponent implements AfterViewInit { @ViewChild('picker') dateRangePicker!: MatDateRangePicker<any>; ngAfterViewInit(): void { // 微延迟确保输入框与picker完成绑定 setTimeout(() => { this.dateRangePicker.open(); }, 0); } onUpdateDateRange(value: any, type: 'from' | 'to') { // 你的日期更新逻辑 } }
补充说明
- 使用
setTimeout(..., 0)是为了让picker的打开操作在Angular的变更检测周期之后执行,确保所有视图元素都已完成初始化和绑定。 - 若你的项目使用了自定义日期适配器,需确保适配器已正确配置,避免额外的初始化问题。
内容的提问来源于stack exchange,提问作者Mads Mønster
相关产品推荐
相关产品推荐

