Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular/HTML input datetime-local with forms and Angular date

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 enter image description here

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?

like image 268
Wouter Vandenputte Avatar asked May 07 '26 15:05

Wouter Vandenputte


1 Answers

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')
      });
  }
like image 182
Sanka Sanjeewa Avatar answered May 10 '26 09:05

Sanka Sanjeewa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!