如何设置Angular Material时间选择器初始默认显示9:00?
实现Angular Material时间选择器面板默认定位到9:00
要实现打开时间选择器面板时自动定位到9:00,同时不设置控件默认值、保留所有可选时间,可以通过监听面板打开事件,手动滚动到目标时间选项的方式实现,具体步骤如下:
1. 模板中绑定面板打开事件
在组件模板里,给mat-timepicker绑定opened事件,触发滚动逻辑:
<input matInput [matTimepicker]="picker" placeholder="选择时间"> <mat-timepicker #picker (opened)="onTimepickerOpened()"></mat-timepicker>
2. 组件类中实现滚动逻辑
在组件类里,监听面板打开事件,等待DOM渲染完成后找到目标时间元素并滚动到可视区域:
import { Component } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { onTimepickerOpened() { // 等待面板DOM渲染完成,避免直接查找元素失败 setTimeout(() => { // 根据时间格式调整选择器:24小时制用[aria-label="09:00"],12小时制区分AM/PM const targetTime = document.querySelector('.mat-timepicker-content .mat-list [aria-label="09:00"]'); if (targetTime) { // 滚动到目标元素并居中显示 (targetTime as HTMLElement).scrollIntoView({ behavior: 'auto', block: 'center' }); } }, 100); } }
注意事项
- 时间格式适配:如果使用12小时制,目标元素的
aria-label会是"9:00 AM"或"9:00 PM",请根据项目配置修改选择器 - DOM类名兼容:不同版本的Angular Material可能调整面板DOM类名,若找不到元素,可通过浏览器开发者工具查看面板结构,修改选择器中的类名
- 延迟时间:
setTimeout的100ms是为确保面板DOM渲染完成,若某些环境下仍找不到元素,可适当延长延迟时间
内容的提问来源于stack exchange,提问作者Pablo Sarturi
相关产品推荐
相关产品推荐

