Angular Material datetime-local输入框默认显示0001年1月,如何设为今日日期?
解决Angular Material datetime-local输入框默认显示今日日期的问题
问题出在你的ndate FormControl未设置初始值,导致datetime-local控件默认显示0001年1月。只需给FormControl设置符合要求的当前日期值即可,具体实现如下:
方法一:初始化FormControl时直接赋值
在组件的TypeScript文件中,创建FormControl时传入格式化后的当前日期:
import { FormControl } from '@angular/forms'; @Component({ // 你的组件元数据(如selector、templateUrl等) }) export class YourComponent { // 将当前日期格式化为datetime-local要求的YYYY-MM-DDTHH:mm格式 ndate = new FormControl(new Date().toISOString().slice(0, 16)); }
方法二:在组件初始化后赋值
如果需要在组件生命周期钩子中设置(比如依赖其他数据加载完成后),可以在ngOnInit中用setValue方法:
import { FormControl, OnInit } from '@angular/forms'; @Component({ // 你的组件元数据 }) export class YourComponent implements OnInit { ndate = new FormControl(); ngOnInit(): void { // 格式化当前日期并赋值 this.ndate.setValue(new Date().toISOString().slice(0, 16)); } }
关键说明
datetime-local控件仅接受YYYY-MM-DDTHH:mm格式的字符串值,new Date().toISOString()会生成包含毫秒的完整ISO字符串,通过slice(0, 16)截取后正好符合格式要求。
内容的提问来源于stack exchange,提问作者Sami In
相关产品推荐
相关产品推荐

