5

Using Angular 4 I try to set a value to an Input of type "date" and I can not do it. The structure of my field is the following:

<input 
    type="date"
    class="form-control"                        
    ([ngModel])="edt_object.list_changedate" 
    (ngModelChange)="edt_object.list_changedate = $event"
    formControlName="list_changedate"
    name="list_changedate"
    id="list_changedate"
    style="width: 228px!important">

And the Typescript code with which I try to set the value is the following:

this.edt_object.list_changedate = this.lista_selected.list_changedate

However, nothing happens. When I assign the value using jQuery (Yes, using Angular and jQuery together) it does work, BUT, when I try to validate that field using Angular, the state of that field is "Invalid" because there is no value to Angular. What should I do?

Luis
  • 2,006
  • 5
  • 31
  • 47
  • 1
    You're doing three times the same thing: once with [(ngModel)], once with (ngModelChange), and once with the formControlName, (which shows you're using a reactive form, and thus shouldn't change ngModel). Post a minimal complete example reproducing the problem. But start by deciding if you want a template-based form or a reactive form. – JB Nizet Nov 28 '17 at 21:22
  • You implement databinding and then don't even utilize it and instead use JQuery? – Zze Nov 28 '17 at 21:31
  • 1
    have you tried removing brackets around ngModel `([ngModel])="edt_object.list_changedate" ` ? – Haifeng Zhang Nov 28 '17 at 21:35
  • Thank you very much everyone for your response. The right answer was given by haifzhan.. – Luis Nov 28 '17 at 22:00

2 Answers2

4

Change

 ([ngModel])="edt_object.list_changedate" 
 (ngModelChange)="edt_object.list_changedate = $event"

to

 [ngModel]="edt_object.list_changedate" 
 (ngModelChange)="onChange($event)"

and implement onChange() as

onChange(event) {
    // emit event
}

[(ngModel)] is two-way binding (ngModelChange) is the @Output of ngModel. If you want to use (ngModelChange) you have to use [ngModel]

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0

As one of the variants of the problem it could be incorrect date format. Try to debug 'this.lista_selected.list_changedate' value. It should be someting like '2016-10-13' format.

Klyuch
  • 66
  • 1
  • 6