Angular 2 Checkbox Two Way Data Binding

Angular 2 Checkbox Two Way Data Binding

You can remove .selected from saveUsername in your checkbox input since saveUsername is a boolean. Instead of [(ngModel)] use [checked]="saveUsername" (change)="saveUsername = !saveUsername"

Edit: Correct Solution:

<input
type="checkbox"
[checked]="saveUsername"
(change)="saveUsername = !saveUsername"/>

Update: Like @newman noticed when ngModel is used in a form it won't work. However, you should use [ngModelOptions] attribute like (tested in Angular 7):

<input
type="checkbox"
[(ngModel)]="saveUsername"
[ngModelOptions]="{standalone: true}"/> `

I also created an example at Stackblitz: https://stackblitz.com/edit/angular-abelrm

two-way binding on checkbox ngFor Angular2

You could use the material2 md-checkbox directive to create styled elements.
In my opinion that is not really two-way binding, its just a combination of 1 way binding in both directions (template - data source and data source - template)

UPDATE:
I created a small plnkr to reproduce your situation: http://plnkr.co/edit/cr7TokiqSaBGli7mgCBM

@Component({
selector: 'my-app',
template: `
<div *ngFor="let element of elements; let i = index;">
<span>Val: {{element}}</span>
<input type="checkbox"
[checked]="element" (change)="handleChange(element, i)">
</div>
`,
})
export class App {
elements= [
false,
true,
false,
]:

handleChange(val: boolean, index: number){
console.log("Index: "+index);
console.log("Val: "+val);
this.elements[index] = !val;
}

The elements in the list are correctly rendered, but the change events will in some cases modify the values of incorrect positions in the elements array. Ill take a furhter look later

UPDATE: refactored plnkr

Please check:
http://plnkr.co/edit/Ich0g5kzSiQINZjh3VYo

I made some changes to the plnkr that u sent me.

I changed the iteration variables from const to let (considering that their values arent constant during execution of the loops).

As I mentioned before, most likely there are 2 posibilities: the classes in .ts are being transpiled in a wrong way to .js (class members are being setted as readonly by default), or there is something wrong in the way that you are manually mapping the values to class instances.

Angular Material Checkbox Two-Way binding

The value may be reset too quickly, when Angular has not completed the change detection cycle triggered by the click. It works if we reset the value asynchronously with setTimeout (see this stackblitz):

handleData(data: TestData) {
console.log(data.isActive);
setTimeout(() => {
data.isActive = false;
});
}

or if we call ChangeDetectofRef.detectChanges() before resetting the value (see this stackblitz):

handleData(data: TestData) {
console.log(data.isActive);
this.changeDetectorRef.detectChanges();
data.isActive = false;
}

Angular Material CheckBox two way binding

Idetodospoca, You can use a [(ngModel)] always you give value to your options, and forget (change)

<mat-list [(ngModel)]="form.delivery_mode">
<mat-list-item *ngFor="let delivery of delivery_modes">
<mat-checkbox [value]="delivery">{{delivery}}</mat-checkbox>
</mat-list-item>
</mat-list>
<!--just for check-->
{{form.delivery_mode|json}}

So, you has a variabe "selectedDeliveries" that is an array

//And you can do by code, e.g.
form.delivery_mode=['delivery1','delivery3']

See a simple example in stackblitz

Angular2 is there a way to use a two way binding with a checkbox?

This is a known issue

  • https://github.com/angular/angular/issues/3406,
  • https://github.com/angular/angular/issues/6311

There are different workarounds like using event.target.checked instead of the value from the model.

You can use

<input type="checkbox"  
(change)="expression && expression.Option1=$event.target.checked ? true : undefiend"
[ngModel]="expression?.Option1">
<input type="checkbox"
(change)="expression && expression.Option2=$event.target.checked ? true : undefiend"
[ngModel]="expression?.Option2">

Plunker example

Two way binding in a list of checkbox in angular JS

It seems that you should use ng-model within your checkbox
something like this:

<div class="col-xs-12">
<div class="col-xs-12" ng-repeat="(i, x) in Nodes track by $index" >
<input type="checkbox" style="width:auto" ng-model="Nodes[i].IsActive" ng-checked="x.IsActive"/>
<label style="width:auto">{{x.NodeName}}</label>
</div>`enter code here`
</div>

How does Angular two-way-data-binding work without a component property?

The property is created on your component class, which is nothing more than an object. If a property does not exist on an object it will return as undefined, which will resolve to false. When you check the checkbox, the ngModel will set componentIntance.something to true. At this point the property will be there, when you uncheck the checkbox after this, the property will still be there, but will now be false.

What you are doing there though, does not work anymore with the latest angular versions and with the strict template check turned on. The compiler will detect that the something property is not declared on the component class and will throw an error during compile phase

two-way data binding of input checkbox element

Solution to your situation

is put all the code of setMain within setTimeout :

setMain() {
setTimeout(() => {
for(let item of this.items){
//set all items` main to false if they are not the selected item
if(this.selectedItem.id != item.id){
item.main = false;
}
//if it is the selected item, set it as the main item
else if(this.selectedItem.id == item.id){
item.main = true;
}
}
})
}

WORKING DEMO

For more detail please check : Angular 2 - Checkbox not kept in sync



Related Topics



Leave a reply



Submit