In my Angular application, I want a user to select a date and a time for an appointment, I am trying to use the
<input matInput type="datetime-local"...>
element for this. But this control needs to be bound to a form, so I created a form
public form: FormGroup;
constructor(_formBuilder: FormBuilder) {
this.form = _formbuilder.group({
datetime: new Date()
});
}
and I wrap the input in this form such that it becomes
<form [formGroup]="form">
<input matInput type="datetime-local" formControlName="datetime">
</form>
This works fine as the date time is inserted in my form but the initial value is simply blank

This remains blank until i start changing it. I assume because the input requires a string? I'd rather give it a date but even giving it a string
constructor(_formBuilder: FormBuilder) {
this.form = _formbuilder.group({
datetime: new Date().toDateString()
});
}
yields the exact same result. So how can I bind it to a Typscript Date object and start displaying it with an initial value?
HTML datetime-local input required 'yyyy-MM-ddTHH:mm' format, but have given date object.
So you use Angular date pipe as another way to convert it.
import { DatePipe } from '@angular/common';
public form: FormGroup;
constructor(
_formBuilder: FormBuilder,
private datePipe: DatePipe,
) {
this.form = _formbuilder.group({
datetime: this.datePipe.transform(new Date(), 'yyyy-MM-ddTHH:mm')
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With