Angular 将值设置为 MatInput 类型时间
Angular Set value to MatInput type time
我有一个时间类型的 matInput 字段,我想设置一个新的 Date () 变量的 HH:mm,当我使用 [value] 时我可以做到,但我想知道如何使用 formControlName 来完成。
component.html
<mat-form-field appearance="outline" class="pl-sm-8 no-errors-spacer" fxFlex="50">
<mat-label>Time:</mat-label>
<input matInput
type="time"
formControlName="Time_start"
required>
</mat-form-field>
component.ts
createComposeForm(): FormGroup
{
return this._formBuilder.group({
Time_start : [''],
});
}
ngOnInit(): void
{
this.form = this.createComposeForm();
let fechaInicioValue = new Date(this.VarWhitTheDate);
this.form.get('Time_start').setValue(= new Date(fechaInicioValue ););
}
你的 HTML 没问题。并确保您的 form-field
嵌套在 form
.
下
而且您必须将日期转换为时间字符串才能工作。
因此,设置值将如下所示:
this.form.get("Time_start").setValue(this.getTimeAsString(fechaInicioValue));
转换函数:
getTimeAsString(date: Date) {
return `${date.getHours()}:${(date.getMinutes() < 10 ? "0" : "") +
date.getMinutes()}`;
}
的工作解决方案
我有一个时间类型的 matInput 字段,我想设置一个新的 Date () 变量的 HH:mm,当我使用 [value] 时我可以做到,但我想知道如何使用 formControlName 来完成。
component.html
<mat-form-field appearance="outline" class="pl-sm-8 no-errors-spacer" fxFlex="50">
<mat-label>Time:</mat-label>
<input matInput
type="time"
formControlName="Time_start"
required>
</mat-form-field>
component.ts
createComposeForm(): FormGroup
{
return this._formBuilder.group({
Time_start : [''],
});
}
ngOnInit(): void
{
this.form = this.createComposeForm();
let fechaInicioValue = new Date(this.VarWhitTheDate);
this.form.get('Time_start').setValue(= new Date(fechaInicioValue ););
}
你的 HTML 没问题。并确保您的 form-field
嵌套在 form
.
而且您必须将日期转换为时间字符串才能工作。
因此,设置值将如下所示:
this.form.get("Time_start").setValue(this.getTimeAsString(fechaInicioValue));
转换函数:
getTimeAsString(date: Date) {
return `${date.getHours()}:${(date.getMinutes() < 10 ? "0" : "") +
date.getMinutes()}`;
}
的工作解决方案