在Angular中,你可以使用ngModel
指令来获取日期选择器的值。以下是一个示例代码:
元素创建一个日期选择器,并使用[(ngModel)]
指令绑定一个变量来获取选择器的值:
selectedDate
变量来存储日期选择器的值:selectedDate: Date;
selectedDate
变量来获取日期选择器的值,并进行相应的操作:// 打印选择的日期
console.log(this.selectedDate);
// 将选择的日期转换为特定格式的字符串
const formattedDate = this.selectedDate.toISOString().substring(0, 10);
console.log(formattedDate);
请注意,selectedDate
变量的类型必须为Date
,否则可能会导致类型错误。你可以在组件中初始化selectedDate
变量为当前日期,以便在没有选择日期时有一个默认值:
selectedDate: Date = new Date();
这样,当用户打开日期选择器时,将显示当前日期。