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?
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.
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.
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.
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 .
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"/>   `
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);   } } 
                        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