0

如何将日期绑定到日期选择器?

const TodayDate = "19-11-2020";
ngOnInit() {
  this._MyregisterForm = this.formBuilder.group({
    today_Date:[this.TodayDate, [Validators.required]]
  });
}

HTML

<form [formGroup]="_MyregisterForm" (ngSubmit)="onSubmit()">
  <input type="date" formControlName="today_Date" value="{{TodayDate}}">
</form>
4

5 回答 5

0

删除value="{{TodayDate }}"您正在将控件与 TodayDate 值绑定,这就足够了。

于 2020-11-19T09:39:54.610 回答
0

我会尝试将日期保留为您的应用程序中的 javascript 日期。它将更容易以不同的方式格式化它们并将它们与角度材料日期选择器一起使用。

使用库 date-fns 将字符串解析为日期。

https://date-fns.org/v2.16.1/docs/parse

然后将该日期传递给 formBuilder。

于 2020-11-19T09:40:19.170 回答
0

使用时无需value在输入中输入属性formControlName

Stackblitz 演示

组件.html

<form [formGroup]="_MyregisterForm" (ngSubmit)="onSubmit()">
    <input type="date" formControlName="today_Date">
    <button type="submit">Submit</button>
</form>

组件.ts

import { Component, VERSION } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { DatePipe } from "@angular/common";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
  providers: [DatePipe]
})
export class AppComponent {
  _MyregisterForm: FormGroup;
  TodayDate = "19-11-2020";

  constructor(private formBuilder: FormBuilder, private datePipe: DatePipe) {
    this._MyregisterForm = this.formBuilder.group({
      today_Date: [this.getTransformedDate(this.TodayDate), Validators.required]
    });
  }

  private getTransformedDate(date) {
    let date1 = date.split("-");
    let newDate = date1[2] + "-" + date1[1] + "-" + date1[0];
    return newDate;
  }

  onSubmit() {
    const date = this.datePipe.transform(
      this._MyregisterForm.get("today_Date").value,
      "dd-MM-yyyy"
    );
    alert(date);
  }
}
于 2020-11-19T09:42:57.650 回答
0

我在这里提供了一个 Stackblitz 。

日期格式不好,需要使用国际格式。而且,就像大家说的,你不需要绑定一个value.

_MyregisterForm: FormGroup;
TodayDate = "2020-12-10";

constructor(private formBuilder: FormBuilder) {
  this._MyregisterForm = this.formBuilder.group({
    today_Date: [this.TodayDate, Validators.required]
  });
}
<form [formGroup]="_MyregisterForm">
    <input type="date" formControlName="today_Date">
</form>
<pre>{{ _MyregisterForm.value | json }}</pre>
于 2020-11-19T09:55:01.200 回答
0

TodayDate应该;

TodayDate = new Date();

并从中删除value属性input

于 2020-11-19T16:54:42.730 回答