如何在Angular Bootstrap datepicker组件加载时将今日设为默认日期

你只需要给双向绑定的变量selectedDateValue赋初始值为格式化后的当日日期即可实现需求,不需要修改现有HTML代码,具体操作如下:
修改TS文件代码
type="date"的原生输入框仅识别YYYY-MM-DD格式的字符串,我们在组件初始化阶段给绑定变量赋值即可:
import { Component, OnInit } from '@angular/core'; @Component({ // 保留你原有的组件配置即可 }) export class YourComponent implements OnInit { selectedDateValue: string; selectedDate: string; ngOnInit(): void { // 方式1:简单快捷,直接用UTC时间格式化 // this.selectedDateValue = new Date().toISOString().split('T')[0]; // 方式2:更推荐,适配本地时区,避免时差导致日期显示错误 this.selectedDateValue = this.getLocalTodayDate(); } // 本地时区日期格式化方法 private getLocalTodayDate(): string { const today = new Date(); const year = today.getFullYear(); const month = String(today.getMonth() + 1).padStart(2, '0'); const day = String(today.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // 原有方法保留不变 searchPayments(type, keyword){ this.selectedDate = keyword; } }
修改完成后页面加载时,日期选择器就会自动填充并显示当日日期,原有选择日期的交互逻辑完全不受影响。
内容的提问来源于stack exchange,提问作者D.Anush
相关产品推荐
相关产品推荐

