本文介绍了Angular:如何在初始化时将时间类型的输入设置为当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用FormBuilder创建了日期和时间输入表单并创建了可工作的html界面
I have created time and date input form with FormBuilder and created working html interface
(create.component.html):
(create.component.html):
<form [formGroup]="createForm" class="create-form">
<mat-form-field class="field-full-width">
<input matInput type="time" placeholder="Time of activity" formControlName="time" #time/>
</mat-form-field>
<mat-form-field class="field-full-width">
<input matInput [matDatepicker]="dp" formControlName="date" #date>
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
</mat-form-field>
(...)
我尝试在此处设置日期(create.component.ts):
I've tried to set date here (create.component.ts):
createForm: FormGroup;
constructor(private entryService: EntryService, private fb: FormBuilder, private router: Router) {
this.createForm = this.fb.group({
time: ['', Validators.required],
date: ['', Validators.required],
});
}
ngOnInit() {
this.createForm.patchValue({
date: new Date(),
time: new Date()
});
}
在DatePicker中效果很好,但没有及时输入:
With good result in DatePicker but not in time input:
如何在表单初始化时设置和显示当前时间?
How can I set and display current time on initialization of form?
推荐答案
所需的格式为类似于HH:mm的字符串,因此,时间类型的输入是这样设置的:
The desired format is string like HH:mm therefore input of time type is set this way:
ngOnInit() {
this.createForm.patchValue({
date: new Date(),
time: new Date().getHours() + ':' + new Date().getMinutes()
});
}
这篇关于Angular:如何在初始化时将时间类型的输入设置为当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!