Angular TypeScript如何分配日期



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

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>

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

Stacklitz演示

component.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);
}
}

Removevalue="{{TodayDate }}"您正在绑定一个具有TodayDate值的控件,这就足够了。

我会尽量将日期作为javascript日期保存在您的应用程序中。这将使它们更容易以不同的方式格式化,并将它们与角度材质日期选择器一起使用。

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

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

然后将该日期传递到表单生成器中。

我在这里提供了一个Stacklitz。

日期格式不好,您需要使用国际格式。此外,正如大家所说,您不需要绑定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>

TodayDate应为;

TodayDate = new Date();

并从input中删除value属性

相关内容

  • 没有找到相关文章

最新更新