Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 checkbox ng-model not updated

I am trying a simple thing with Angular 2.0 I want a bind a model to an 'input checkbox', register the 'change' with a method, have the method executed when the checkbox state is changed and act based on the state of the model. Everything works but, when the method linked with the change event is executed, the state of the model is the contrary of what I expect, i.e. is false when the checkbox is selected, is true when the checkbox is unselected. Here is the code snippet;

<input value={{object.name}} type="checkbox" [(ng-model)]="object.selected" (change)="onChange(object.selected)">

Any idea about what I am doing wrong?

like image 363
Picci Avatar asked Dec 20 '15 09:12

Picci


4 Answers

As of angular2.beta8 this simple trick will do

<input type="checkbox" [(ngModel)]="object.selected" /> 

From Angular 4, must add the name attribute for this to bind.

<input type="checkbox" [(ngModel)]="object.selected" name="element_name"/> 
like image 150
Anderson Fortaleza Avatar answered Sep 24 '22 01:09

Anderson Fortaleza


A way to do it without ngModel

<input     id="{{fieldId}}"     type="checkbox"     [checked]="displayValue"     (click)="setDisplayValue($event.target.checked)" > 

displayValue would be getter/setter setDisplayValue() method will update the record and hence displayValue would be updated

like image 34
Nugu Avatar answered Sep 26 '22 01:09

Nugu


For me only works when I used (ngModelChange):

<input type="checkbox" 
       [(ngModel)]="object.selected" 
       (ngModelChange)="onChange(object.selected)">

If I use (change) or (click) the state is always contrary of what I expect, as you said

like image 35
Kayo Lima Avatar answered Sep 24 '22 01:09

Kayo Lima


I have implemented it like this: <input #angularcb type="checkbox" (change)="angular = angularcb.checked" />

You can also see more details and a live demo here: http://www.syntaxsuccess.com/viewarticle/input-controls-in-angular-2.0 http://www.syntaxsuccess.com/angular-2-samples/#/demo/input

like image 33
TGH Avatar answered Sep 23 '22 01:09

TGH