Angular Material:如何将mat-datepicker默认显示日期设置为昨日日期
解决mat-datepicker无法显示昨日日期的问题
我来帮你搞定这个问题!你遇到的核心问题是对setDate()方法的返回值理解有误,导致FormControl传入了组件无法识别的类型。
问题根源
yesterday.setDate(this.yesterday.getDate() - 1)这个操作确实会把日期改成昨天,但它的返回值是Unix时间戳(数字类型),而mat-datepicker的FormControl需要接收的是Date类型的对象。你把数字传给FormControl后,组件没法将其解析为有效日期,自然就不会显示任何内容。
修正后的代码
app.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; export class ApplicantComponent implements OnInit { onlineDate: FormControl; currentDate = new Date(); yesterday: Date; constructor() { // 先创建昨日的Date对象 this.yesterday = new Date(); this.yesterday.setDate(this.yesterday.getDate() - 1); // 用Date对象初始化FormControl this.onlineDate = new FormControl(this.yesterday); } ngOnInit(): void { // 如果你更习惯在生命周期钩子中初始化,也可以这么写: // this.yesterday = new Date(); // this.yesterday.setDate(this.yesterday.getDate() - 1); // this.onlineDate.setValue(this.yesterday); } }
app.component.html(保持你的原有代码即可)
<mat-form-field class="example-full-width" [floatLabel]="hideLabel"> <input matInput [formControl]="onlineDate" name="onlineDate" [max]="currentDate" [matDatepicker]="picker" required placeholder="Online Date " autocomplete="off" /> <mat-datepicker-toggle matSuffix [for]="picker"> </mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field>
关键说明
setDate()会直接修改原Date对象,所以我们先创建完整的Date实例,调整日期后,再把这个Date对象传给FormControl。- 确保FormControl的初始值是有效的
Date类型,mat-datepicker才能正确识别并渲染出昨日日期。
内容的提问来源于stack exchange,提问作者Techdive
相关产品推荐
相关产品推荐

