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.
As per HTML5, you can use
input type="datetime-local"
instead ofinput type="date"
.It will allow the
[(ngModel)]
directive to read and write value from input control.Note: If the date string contains 'Z' then to implement above solution, you need to trim the 'Z' character from date.
For more details, please go through this link on mozilla docs.
Angular 2 completely ignores
type=date
. If you change type totext
you'll see that yourinput
has two-way binding.Here is pretty bad advise with better one to follow:
My project originally used
jQuery
. So, I'm usingjQuery datepicker
for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI,input=date
doesn't work in Firefox.Good advise: There are few pretty good
Angular2 datepickers
:https://github.com/emirdeliz/meus-projetos/tree/master/angular2-schedule/app/frontend/components/datepicker
https://github.com/MrPardeep/Angular2-DatePicker
https://www.npmjs.com/package/ng2-datepicker
In .ts :
.html: