3

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?

3 Answers 3

3

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')
      });
  }
Sign up to request clarification or add additional context in comments.

Comments

3

I managed to make it working in this way (Angular 2+, Reactive Forms):

my.component.html:

<input type="datetime-local" formControlName="myDateTime">

my.component.ts:

import { formatDate } from '@angular/common';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-my-component',
  templateUrl: './my.component.html',
  styleUrls: []
})
export class MyComponent implements OnInit {
myForm: FormGroup;
now: Date = new Date();

constructor(private fb: FormBuilder) {

    this.myForm = this.fb.group({
      myDateTime: [formatDate(this.now, 'yyyy-MM-ddTHH:mm', 'en'), [Validators.required]]
    });
}

//..
}

The most critical part to notice is the date pattern formatted inside formatDate() function that should be compliant with HTML 5 specifications (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local).

This made the difference, in my case.

Comments

0

Also, you can use any of the formats described here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.