How to assign value to datetime-local in a Reactive Form
Asked Answered
R

2

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

Recur answered 14/4, 2018 at 9:36 Comment(3)
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)Low
@Low Thanks for your suggestion. Hard coded string works perfectly but I want to assign system's current date and time to the datetime-local.Recur
use new Date().toString() or some like, see, e.g #1057228Low
A
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)),
});
Alessandro answered 2/5, 2019 at 10:59 Comment(0)
S
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 { }
Sampling answered 26/5, 2023 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.