Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: NgModel doesn't work. Does not set value to "date" field

Tags:

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?

like image 668
Ricky Avatar asked Nov 28 '17 21:11

Ricky


People also ask

What is [( ngModel )]?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, 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 form validations.

Can I use ngModelChange without ngModel?

ngModelChange need ngModel class to function. change event bound to classical input change event. ngModelChange It fires when the model changes. You cannot use this event without ngModel directive.

Can't bind to ngModel since it isn't a known property of input Ng?

To fix Can't bind to 'ngModel' since it isn't a known property of 'input' error in Angular applications we have to import FormModule in app. module. ts file. If you are using FormBuilder class to create reactive form we have to import ReactiveFormsModule as well to avoid below error.

What is the difference between ngModel and ngModelChange?

The NgModel class has the update property with an EventEmitter instance bound to it. This means we can't use (ngModelChange) without ngModel . Whereas the (change) event can be used anywhere, and I've demonstrated that above with the [value] property binding instead.


1 Answers

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]

like image 172
Haifeng Zhang Avatar answered Oct 15 '22 16:10

Haifeng Zhang