1

我正在尝试一种反应形式,其中用户使用 mat-datepicker 输入了一些日期。我面临的问题是 mat-datepicker 的输出是一个包含日期的时刻对象。我想获取字符串中的日期(例如:“YYYY-MM-DD”)而不是对象。

目前,我的表单组件的 html 模板如下所示:

<form [formGroup]="myForm">
<mat-form-field>
    <mat-label>Date d'expiration</mat-label>
    <input matInput [matDatepicker]="picker" formControlName="expireDate">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

而且,我的组件看起来像这样:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
declare var require: any
const moment = require('moment');
@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
})
export class FormComponent implements OnInit{
  myForm : FormGroup;
  constructor(private fb: FormBuilder) { }
  ngOnInit(): void {
    this.myForm =  this.fb.group({
      expireDate: [moment(),[
        Validators.required,
      ]],
    });
  }
}

提前致谢!

4

2 回答 2

1

您可以像以下示例一样格式化时刻日期对象:

const currentDate = moment();
moment(currentDate).format('YYYY-MM-DD');
于 2021-07-26T16:36:09.437 回答
1

HTML

<form [formGroup]="myForm">
  <mat-form-field>
    <mat-label>Date d'expiration</mat-label>
    <input matInput [matDatepicker]="picker" formControlName="expireDate" (dateChange)="changeDatePicker()">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>
</form>

TS

在表单组中为过期日期赋值

 changeDatePicker(): any {
        this.myForm.value.expireDate = moment(this.myForm.value.expireDate).format('YYYY-MM-DD');
      }
  • 对于多个日期选择器

HTML

<form [formGroup]="myForm">
  <mat-form-field>
    <mat-label>Date d'expiration</mat-label>
    <input matInput [matDatepicker]="picker" formControlName="expireDate" (dateChange)="changeDatePicker()">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Date d'expiration</mat-label>
    <input matInput [matDatepicker]="picker1" formControlName="expireDate2" (dateChange)="changeDatePicker()">
    <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
    <mat-datepicker #picker1></mat-datepicker>
  </mat-form-field>
</form>

TS

myForm = this.fb.group({
    expireDate: ['', Validators.required],
    expireDate2: ['', Validators.required],
  });

changeDatePicker(): any {
    this.myForm.value.expireDate = (moment(this.myForm.value.expireDate).format('YYYY-MM-DD'));
    this.myForm.value.expireDate2 = (moment(this.myForm.value.expireDate2).format('YYYY-MM-DD'));
  }
于 2021-07-26T17:30:50.280 回答