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?
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"/>
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With