Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: 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?

like image 590
stijn.aerts Avatar asked May 05 '16 16:05

stijn.aerts


People also ask

What is the proper way of two-way data binding in angular 2?

Angular's two-way binding syntax is a combination of square brackets and parentheses, [()] . The [()] syntax combines the brackets of property binding, [] , with the parentheses of event binding, () , as follows.

How do you bind data in ngModel?

ngModel Directive[()] = [] + () where [] binds attribute, and () binds an event. The [(ngModel)] syntax is the recommended way of two-way data binding. The ngModel directive with [] syntax is used for one-way data binding. [ngModel] binds a value to a property to UI control.

What does [( ngModel )] mean?

ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form. We can use ngModel with: input. text.

Is ngModel two-way binding?

The Angular uses the ngModel directive to achieve the two-way binding on HTML Form elements. It binds to a form element like input , select , selectarea .


1 Answers

UPDATE:

StackBlitz

when I wrote this answer DatePipe did not exist, now you can just do this

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

`


Old Answer:

PLUNKER

You need to convert date object in the input type="date" format which is yyyy-mm-dd, this is how it will work

Template:

<input [(ngModel)]="humanDate" type="date" name="startDate"/> 

Component (TS):

export class App {   startDate: any;    constructor() {     this.startDate = new Date(2005, 1, 4);   }    set humanDate(e){     e = e.split('-');     let d = new Date(Date.UTC(e[0], e[1]-1, e[2]));     this.startDate.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());   }    get humanDate(){     return this.startDate.toISOString().substring(0, 10);   } } 
like image 180
Ankit Singh Avatar answered Sep 26 '22 11:09

Ankit Singh