typescript 如何从Angular Material中的DatePicker获取FormControl中的日期

k4ymrczo  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(127)

如何从Angular Material中的DatePicker获取FormControl中的日期
HTML:

<input matInput [matDatepicker]="dp_" formControlName="fechaSolicitud" 
        (dateChange)="showDate()">
<mat-datepicker-toggle matIconSuffix [for]="dp_"></mat-datepicker-toggle>
<mat-datepicker #dp_></mat-datepicker>

TS:

PayFormGroup=new FormGroup({
...
fechaSolicitud: new FormControl('',[Validators.required]),
...
})

showDate(){
console.log(this.PayFormGroup.get('fechaSolicitud')?.value)
}

我得到这个结果,但我想要的日期enter image description here

whhtz7ly

whhtz7ly1#

您将获得一个Moment对象。这意味着您的日期选择器(库)以与the moment library一起工作的方式配置,并相应地返回Moment对象。您可以使用以下行轻松地将返回的结果更改为日期字符串:

const date: string = value.format('YYYY-MM-DD');

或者使用以下行替换到原生Javascript Date类:

const date: Date = value.toDate();

其中value是您在屏幕截图中显示的Moment对象。
对于其他格式,我将参考the official Moment documentation

相关问题