5

I am unable to assign value to `datetime-local element in a form.

Code from template:

Code from HTML template

Code from typescript file:

let dateTime : Date = new Date();

this.testForm = this.formBuilder.group({    
  'dateTime': new FormControl(dateTime),
});

Result:

enter image description here

What is the proper way to assign date & time to datetime-local using typescript

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Robert Williams
  • 1,370
  • 1
  • 17
  • 38
  • type datetime-local is a "string" type, so you can do this.testForm = this.formBuilder.group({ 'dateTime': '2017-06-01T08:30', });. Anyway, I suggested NOT use type datetime-local. This don't work in all navigators (e.g. you see as "normal" input in FireFox) – Eliseo Apr 14 '18 at 12:28
  • @Eliseo Thanks for your suggestion. Hard coded string works perfectly but I want to assign system's current date and time to the datetime-local. – Robert Williams Apr 14 '18 at 12:37
  • use new Date().toString() or some like, see, e.g https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – Eliseo Apr 14 '18 at 13:38

2 Answers2

8

datetime-local requires value in specific format (yyyy-mm-ddThh:mm)

You can try the following,

const dateTime = new Date();
this.testForm = this.formBuilder.group({    
  dateTime: new FormControl(dateTime.toISOString().substring(0, 16)),
});
Yuvaraj V
  • 1,020
  • 2
  • 16
  • 28
1

You can find the official docs here. Output from the console:

The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".

I used DatePipe for this, but you could go with formatDate also (see here for more).

In your component:

import { DatePipe } from '@angular/common';

constructor(
    private datePipe: DatePipe
)

ngOnInit() {
    this.dateControl.setValue(this.datePipe.transform(this.defaultValues, 'yyyy-MM-ddTHH:mm:ss'));
}

In your module declarations (e.g. app.module.ts) add DatePipe:

import { DatePipe } from '@angular/common';

@NgModule({
    declarations: [
        AppComponent,
        // ...
    ],
    imports: [
        // ...

    ],
    providers: [
        DatePipe,
        // ...
    ],
    exports: // ...
    bootstrap: [AppComponent]
})
export class AppModule { }
testing
  • 19,681
  • 50
  • 236
  • 417