Here is my simple code that works only for 'title'. 'docdatetime' control appears blank. What am I doing wrong?
//template ===================================================
<div class="form-group">
  <input type="text" id="title" formControlName="title" class="form-control">
</div>
<div class="form-group">
  <input type="datetime-local" id="docdatetime" formControlName="docdatetime" class="form-control">
</div>
//component.ts ===============================================
import { FormGroup, FormControl } from '@angular/forms';
..... 
export class..... 
    docForm: FormGroup;
    ngOnInit() {
        let docTitle = 'My first document';
        let docDate = 'Jun 15, 2015, 9:43:11 PM';
        this.docForm = new FormGroup({
            'title': new FormControl(docTitle),
            'docdatetime': new FormControl(new Date(docDate))
        });
    }   

The reason for this error is that the DatetimeLocal property on the input requires a very specific format, being YYYY-MM-DDTHH:MM:SS.SSS. This format is known as an ISO Date. So to fix your error, you have to pass in a date in that format. HOWEVER, an actual ISO Date's format is YYYY-MM-DDTHH:MM:SS.SSSZ. The Z refers to the timezone, which is always zero UTC offset. Look here for information on ToISOString(). So, an easy fix for that is to simply slice off the last character, which will always be the character Z in the new Date().toISOString().
let docTitle = 'My first document';
let docDate = 'Jun 15, 2015, 21:43:11 UTC'; //You'll want to change this to UTC or it can mess up your date.
this.docForm = new FormGroup({
    'title': new FormControl(docTitle),
    'docdatetime': new FormControl(new Date(docDate).toISOString().slice(0, -1))
});
This means that the value you receive from that input will NOT be an actual Date. It'll be a string. So if you need it to be a date later on, make sure you create a New Date() using the value of the string and you should be good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With