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.
If you are using a modern browser there's a simple solution.
First, attach a template variable to the input.
Then pass the variable into your receiving method.
In your controller just accept the parameter as type HTMLInputElement and use the method valueAsDate on the HTMLInputElement.
You can then manipulate the date anyway you would a normal date.
You can also set the value of your
<input [value]= "...">
as you would normally.Personally, as someone trying to stay true to the unidirectional data flow, i try to stay away from two way data binding in my components.
you can use a workaround, like this:
on your component :
Instead of [(ngModel)] you can use:
You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example).
In your component
and in your html
Angular 2 , 4 and 5 :
the simplest way : plunker
use DatePipe