Angular 2 / Material 2: Checkbox checked binding

3.7k Views Asked by At

I have an Angular 2 (2.4.3) app using Material (2.0.0-beta.1) and I'm facing some problems with bindings on checkboxes.

I want to have a checkbox that's conditionally checked according to a boolean value in my component. When clicked, I want to toggle the bool.

So I did this:

private _showName: boolean = true;

and in the HTML:

<md-checkbox (click)="toggleName()" [checked]="_showName"></md-checkbox>

And toggleName() looks like this:

toggleName(): void { 
    this._showName = !this._showName;
    let ctrl = this._searchForm.get('name'); 
    ctrl.enabled ? ctrl.disable() : ctrl.enable(); 
}

Using this, when I click the checkbox:

  • The bool _showName gets toggled to false
  • But the checkbox stays checked

The second time I click the checkbox it unchecks itself and toggles the bool again, hence leaving the logic reversed.

If I set [checked] using a string like this:

<md-checkbox (click)="toggleName()" [checked]="true"></md-checkbox>

The checkbox unchecks itself on the first click and the bool is toggled, but now there's no way for me to bind it to the bool. So if I change the bool from my component it won't reflect to the checkbox.

I am probably doing something wrong, but looking at "Examples" in the official documentation I can't figure out where I am going wrong.

2

There are 2 best solutions below

0
Poul Kruijt On

The problem is that you check and uncheck it immediately. Remove the [checked] binding, and don't do the this._showName = !this._showName; inside the toggleName() method:

toggleName(): void {
    let ctrl = this._searchForm.get('name'); 
    ctrl.enabled ? ctrl.disable() : ctrl.enable(); 
}

template:

<md-checkbox (click)="toggleName()"></md-checkbox>

When you click it gets checked and unchecked automatically. But you unchecked, or checked it yourself again by setting this._showName.

0
N0mi On

The best way would be rather to data bind the variable with the md-checkbox control.

      <md-checkbox  [(ngModel)]="_showName">{{_showName }}

The Material component comes with a good documentation and plunker examples. Here is how you can find them How to open examples in plunker.

Also if you click "<" or ">", you can browse through the source code while being on the page