问题
I have created time and date input form with FormBuilder and created working html interface
(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>
(...)
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()
});
}
With good result in DatePicker but not in time input:
How can I set and display current time on initialization of form?
回答1:
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()
});
}
来源:https://stackoverflow.com/questions/51483479/angular-how-to-set-input-of-time-type-to-current-time-on-initialization