Angular 2 Date Input not binding to date value

MoSheikh picture MoSheikh · Jul 4, 2016 · Viewed 155.1k times · Source

trying to get a form set up but for some reason, the Date input in my html is not binding to the object's date value, despite using [(ngModel)]

html:

<input type='date' #myDate [(ngModel)]='demoUser.date'/><br>

form component:

export class FormComponent {
    demoUser = new User(0, '', '', '', '', new Date(), '', 0, [], []);  
}

User class:

export class User {
    constructor (
        public id: number,
        public email: string,
        public password: string,
        public firstName: string,
        public lastName: string,
        public date: Date,
        public gender: string,
        public weight: number,
        public dietRestrictions: string[],
        public fitnessGoals: string[]
    ){

    }
}

A test output reveals the current "new" Date as the object's value, but the input doesn't update the User object's date value or reflect the value, suggesting neither of the two-way bindings are working. Help would be greatly appreciated.

Answer

Bougarfaoui El houcine picture Bougarfaoui El houcine · Mar 24, 2017

Angular 2 , 4 and 5 :

the simplest way : plunker

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">