Angular Material mat-slide-toggle绑定formControlName后[checked]属性失效问题
解决mat-slide-toggle始终选中的问题
问题出在你同时使用了[checked]和formControlName——当通过formControlName绑定表单控件时,Angular表单会完全接管控件的状态,[checked]属性会被忽略,所以你设置的false不会生效。
解决思路:
- 移除模板中的
[checked]属性,保留formControlName即可:<mat-slide-toggle color="primary" formControlName="{{input.id}}"></mat-slide-toggle> - 在组件类中,给对应的FormControl设置初始值为
false:
如果是直接创建FormControl:
如果用FormBuilder简化写法:// 假设你的表单实例名为yourForm this.yourForm = new FormGroup({ [this.input.id]: new FormControl(false) });this.yourForm = this.fb.group({ [this.input.id]: [false] }); - 如果是异步场景(比如从后端加载数据后初始化),可以用
patchValue更新控件状态:this.yourForm.patchValue({ [this.input.id]: false });
内容的提问来源于stack exchange,提问作者NCoding
相关产品推荐
相关产品推荐

