将 mat-datepicker 转换为字符串

Convert a mat-datepicker into a String

我正在尝试使用一种反应形式,其中有一些日期是由用户使用 mat-datepicker 输入的。我面临的问题是 mat-datepicker 的输出是一个包含日期的 moment 对象。我想获取字符串中的日期(例如:“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>
</form>

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

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,
      ]],
    });
  }
}

提前致谢!

您可以格式化 时刻 日期对象,如下例所示:

const currentDate = moment();
moment(currentDate).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>
</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'));
  }