Angular 2 Checkbox Two Way Data Binding
Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.
Instead the simple:
<input [(ngModel)]="checkboxFlag" type="checkbox"/>
will do two-way binding for checkbox.
Afterwards, when Model checkboxFlag is changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.
To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
Just to complete this answer you should include the import { FormsModule } from '@angular/forms'
into app.module.ts
and add to imports array i.e
import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
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