[英]Angular 2 / Material 2: Checkbox checked binding
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.我有一个使用 Material (2.0.0-beta.1) 的 Angular 2 (2.4.3) 应用程序,但我在复选框绑定方面遇到了一些问题。
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:并在 HTML 中:
<md-checkbox (click)="toggleName()" [checked]="_showName"></md-checkbox>
And toggleName()
looks like this:并且
toggleName()
看起来像这样:
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:使用这个,当我点击复选框时:
_showName
gets toggled to false _showName
被切换为 falseThe 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:如果我使用这样的字符串设置
[checked]
:
<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.该复选框在第一次单击时取消选中并切换 bool,但现在我无法将其绑定到 bool。 So if I change the bool from my component it won't reflect to the checkbox.
因此,如果我从组件更改 bool,它不会反映到复选框。
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 best way would be rather to data bind the variable with the md-checkbox control.最好的方法是将变量与 md-checkbox 控件进行数据绑定。
<md-checkbox [(ngModel)]="_showName">{{_showName }}
The Material component comes with a good documentation and plunker examples. Material 组件带有一个很好的文档和 plunker 示例。 Here is how you can find them How to open examples in plunker .
您可以通过以下方式找到它们如何在 plunker 中打开示例。
Also if you click "<" or ">", you can browse through the source code while being on the page此外,如果您单击“<”或“>”,您可以在页面上浏览源代码
The problem is that you check and uncheck it immediately.问题是您立即选中并取消选中它。 Remove the
[checked]
binding, and don't do the this._showName = !this._showName;
移除
[checked]
绑定,不要执行this._showName = !this._showName;
inside the toggleName()
method:在
toggleName()
方法中:
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.
但是您取消选中,或者通过设置 this._showName 再次检查它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.