stijn26 stijn26 - 6 months ago 173
Javascript Question

Angular2: How to use JavaScript Date Object with NgModel two way binding

I'm working with Angular 2 and I have this code:

JS, this code initiates the employee-variable for the template:

handleEmployee(employee : Employee){
this.employee = employee;
this.employee.startDate = new Date('2005/01/01');
console.log(this.employee);
}


Template:

...
<div>
<label>Start date: </label>
<input [(ngModel)]="employee.startDate" type="date" name="startDate"/>
</div>
<div>
...


Other data like firstname is displayed correctly. But for the date I just get:

mm/dd/yyyy


In the input element, which should be a date.

How can I do this?

Answer

Fixed it with this code:

handleEmployee(employee : Employee){
        this.employee = employee;

        let dateString : string = employee.startDate.toString();
        let days : number = parseInt(dateString.substring(8, 10));
        let months : number = parseInt(dateString.substring(5, 7));
        let years : number = parseInt(dateString.substring(0, 5));
        let goodDate : Date = new Date(years + "/" + months + "/" + days);
        goodDate.setDate(goodDate.getDate() + 2);
        this.date = goodDate.toISOString().substring(0, 10);
    }

Html:

<div>
    <label>Start date: </label>
    <input [(ngModel)]="date" type="date" name="startDate"/>
  </div>