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
_showNamegets 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.
The problem is that you check and uncheck it immediately. Remove the
[checked]binding, and don't do thethis._showName = !this._showName;inside thetoggleName()method:template:
When you click it gets checked and unchecked automatically. But you unchecked, or checked it yourself again by setting this._showName.