You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:43:10