Angular Material升级至15后日期选择器日历选中日期对齐异常
解决Angular Material 12升级到15后日期选择器对齐异常问题
问题现象
Angular Material从12版本升级到15后,日期选择器日历的选中日期出现对齐异常,点击页面任意位置或切换窗口后,对齐问题自动消失。尝试在打开日历时调用ChangeDetectorRef.detectChanges(),未解决问题。
问题代码
HTML代码
<mat-form-field style="width: 100%"> <mat-label>{{ lable }}</mat-label> <input matInput [value]="defaultValue" [min]="minDate" [max]="maxDate" [matDatepicker]="picker" (click)="open()" (focus)="open()" (dateChange)="emitDate($event.value)"/> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker [touchUi]="isMobile$ | async" #picker></mat-datepicker> </mat-form-field>
TypeScript代码
open() { this.picker.open(); this.cRef.detectChanges() }
异常效果截图:
解决方案
方案1:延迟触发变更检测
弹窗渲染存在时序问题,延迟调用变更检测可确保日历完全渲染后再更新:
open() { this.picker.open(); setTimeout(() => { this.cRef.detectChanges(); }, 0); }
方案2:强制触发日历重绘
通过修改元素样式触发浏览器重绘,修正布局异常:
import { ViewChild } from '@angular/core'; @ViewChild('picker') picker: any; open() { this.picker.open(); setTimeout(() => { const calendarElement = this.picker._calendar._elementRef.nativeElement; // 触发重绘流程 calendarElement.style.display = 'none'; void calendarElement.offsetHeight; // 强制浏览器计算布局 calendarElement.style.display = ''; }, 0); }
方案3:升级到Angular Material 15最新补丁版
该对齐问题可能是15早期版本的已知Bug,升级到15.x系列最新补丁版本(如15.2.9及以上),官方大概率已修复该渲染时序问题。
方案4:调整touchUi绑定方式
isMobile$异步Observable可能导致日历初始化时布局计算错误,提前解析值再绑定:
isMobile: boolean = false; ngOnInit() { this.isMobile$.subscribe(value => { this.isMobile = value; this.cRef.detectChanges(); }); }
修改HTML绑定:
<mat-datepicker [touchUi]="isMobile" #picker></mat-datepicker>
内容的提问来源于stack exchange,提问作者siddhesh padhye
相关产品推荐
相关产品推荐

