Robert Williams
Robert Williams

Reputation: 1410

How to assign value to datetime-local in a Reactive Form

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

Upvotes: 5

Views: 4463

Answers (2)

testing
testing

Reputation: 20279

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 { }

Upvotes: 1

Yuvaraj V
Yuvaraj V

Reputation: 1212

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)),
});

Upvotes: 8

Related Questions