Angular 2 Checkbox Two-way data binding

I am new to Angular2 and I have a little problem:

In my Login-Component-HTML, I have two flags that I want to link in two ways: data binding to Login-Component-TypeScript.

This is HTML:

<div class="checkbox"> <label> <input #saveUsername [(ngModel)]="saveUsername.selected" type="checkbox" data-toggle="toggle">Save username </label> </div> 

And this is Component.ts:

 import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Variables } from '../../services/variables'; @Component({ selector: 'login', moduleId: module.id, templateUrl: 'login.component.html', styleUrls: ['login.component.css'] }) export class LoginComponent implements OnInit { private saveUsername: boolean = true; private autoLogin: boolean = true; constructor(private router: Router, private variables: Variables) { } ngOnInit() { this.loginValid = false; // Get user name from local storage if you want to save if (window.localStorage.getItem("username") === null) { this.saveUsername = true; this.autoLogin = true; console.log(this.saveUsername, this.autoLogin); } else { console.log("init", window.localStorage.getItem("username")); } } login(username: string, password: string, saveUsername: boolean, autoLogin: boolean) { this.variables.setUsername(username); this.variables.setPassword(password); this.variables.setIsLoggedIn(true); console.log(saveUsername, autoLogin); //this.router.navigate(['dashboard']); } 

If I click the checkbox, I get the correct value in the controller (component).

But if I change the value, for example, saveUsername in the component, the checkbox will not β€œreceive” the new value.

Therefore, I cannot manipulate the flag from the Component (as I want to do in ngOnInit in the component).

Thanks for your help!

+159
html checkbox angular data-binding typescript
Oct 24 '16 at 9:12
source share
12 answers

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

Change: correct solution:

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

Update: As @newman noted, when ngModel used in a form, it will not work. However, you must use the [ngModelOptions] attribute as (tested in Angular 7):

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

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

+278
Oct 24 '16 at 9:16
source share

Unfortunately, the solution provided by @hakani is not two-way binding . It just handles a one-way changing model from the UI / FrontEnd part.

Instead, it's simple:

 <input [(ngModel)]="checkboxFlag" type="checkbox"/> 

will do two-way binding for the flag.

Subsequently, when the Model checkboxFlag is changed from the Backend or part of the user interface - voila, checkboxFlag saves the actual state of the flag.

Of course, I prepared the Plunker code to present the result: https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk

To complete this answer, you must include import { FormsModule } from '@angular/forms' in app.module.ts and add it to the import array, i.e. app.module.ts

 import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] }) 
+80
Mar 13 '17 at 10:51 on
source share

I work with Angular5, and I had to add the attribute "name" for the binding to work ... "id" is not required for the binding.

 <input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe"> 
+29
Dec 13 '17 at 18:33
source share

I prefer something more explicit:

component.html

 <input #saveUserNameCheckBox id="saveUserNameCheckBox" type="checkbox" [checked]="saveUsername" (change)="onSaveUsernameChanged(saveUserNameCheckBox.checked)" /> 

component.ts

 public saveUsername:boolean; public onSaveUsernameChanged(value:boolean){ this.saveUsername = value; } 
+21
Aug 18 '17 at 11:58 on
source share

Using the syntax <abc [(bar)]="foo"/> on angular.

This means: <abc [bar]="foo" (barChange)="foo = $event" />

This means that your component must have:

 @Input() bar; @Output() barChange = new EventEmitter(); 
+5
Sep 21 '17 at 19:41
source share

You can simply use something like this for two way data binding:

 <input type="checkbox" [checked]="model.property" (change)="model.property = !model.consent_obtained_ind"> 
+4
Jan 31 '17 at 15:34
source share

To complete the checkbox, you must follow these steps:

  • import FormsModule in your module
  • Put the input inside the form tag
  • your entry should look like this:

     <input name="mpf" type="checkbox" [(ngModel)]="value" /> 

    Note. Be sure to include the name on your entry.

+3
Oct. 12 '17 at 22:11
source share

I performed a special component tried in two ways of binding

MyComponent: <input type="checkbox" [(ngModel)]="model" >

 _model: boolean; @Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>(); @Input('checked') set model(checked: boolean) { this._model = checked; this.checked.emit(this._model); console.log('@Input(setmodel'+checked); } get model() { return this._model; } 

strange that it works

 <mycheckbox [checked]="isChecked" (checked)="isChecked = $event"> 

while this wont

 <mycheckbox [(checked)]="isChecked"> 
+2
Aug 31 '17 at 12:43 on
source share

You must add the attribute name="selected" to the input element.

For example:

 <div class="checkbox"> <label> <input name="selected" [(ngModel)]="saveUsername.selected" type="checkbox">Save username </label> </div> 
+2
Feb 28 '18 at 13:04 on
source share

In any situation, if you need to associate a value with a flag that is not logical, then you can try the following options

In the HTML file:

 <div class="checkbox"> <label for="favorite-animal">Without boolean Value</label> <input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'" (change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'"> </div> 

in component ischeckedWithOutBoolean: any = 'Y';

See the stack https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html

+1
Feb 08 '19 at 5:22
source share

A workaround to achieve the same, especially if you want to use a flag with a for loop, is to save the state of the flag inside the array and change it based on the *ngFor loop index. Thus, you can change the state of the checkbox in your component.

app.component.html

<div *ngFor="let item of items; index as i"> <input type="checkbox" [checked]="category[i]" (change)="checkChange(i)"> {{item.name}} </div>

app.component.ts

 items = [ {'name':'salad'}, {'name':'juice'}, {'name':'dessert'}, {'name':'combo'} ]; category= [] checkChange(i){ if (this.category[i]){ this.category[i] = !this.category[i]; } else{ this.category[i] = true; } } 
0
Aug 19 '19 at 1:20
source share

My angular directive like angularjs (ng-true-value ng-false-value)

 @Directive({ selector: 'input[type=checkbox][checkModel]' }) export class checkboxDirective { @Input() checkModel:any; @Input() trueValue:any; @Input() falseValue:any; @Output() checkModelChange = new EventEmitter<any>(); constructor(private el: ElementRef) { } ngOnInit() { this.el.nativeElement.checked = this.checkModel==this.trueValue; } @HostListener('change', ['$event']) onChange(event:any) { this.checkModel = event.target.checked ? this.trueValue : this.falseValue; this.checkModelChange.emit(this.checkModel); } } 

HTML

 <input type="checkbox" [(checkModel)]="check" [trueValue]="1" [falseValue]="0"> 
0
Aug 28 '19 at 19:22
source share



All Articles