You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:
    // 假设你的表单实例名为yourForm
    this.yourForm = new FormGroup({
      [this.input.id]: new FormControl(false)
    });
    
    如果用FormBuilder简化写法:
    this.yourForm = this.fb.group({
      [this.input.id]: [false]
    });
    
  • 如果是异步场景(比如从后端加载数据后初始化),可以用patchValue更新控件状态:
    this.yourForm.patchValue({
      [this.input.id]: false
    });
    

内容的提问来源于stack exchange,提问作者NCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:33:38