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

如何将函数调用结果存入formControlName?遇TypeError读取writeValue错误

问题分析与解决方案

错误信息

12main.js:1 ERROR TypeError: Cannot read properties of null (reading 'writeValue')
    at xe (main.js:1:4203086)
    at Oe.value (main.js:1:4234720)
    at Oe.value (main.js:1:4239942)
    at Oe.value (main.js:1:4239315)
    at Oe.Hs (main.js:1:4058639)
    at cn (main.js:1:4063595)
    at Zt (main.js:1:4063393)
    at rt (main.js:1:4063115)
    at r_ (main.js:1:4091203)
    at Object.y0 (main.js:1:4091050)

问题场景

想要把函数调用结果存入formControlName对应的控件中,触发了上述错误。

关联HTML代码

<div>
<button mat-fab
    color="primary" 
    disabled 
formControlName="TypeSelected"
>   
    {{selectedRequestType(requestForm.value)}}
</button>
</div>

关联TS函数

export class RequestBusComponent implements OnInit {
selectedRequestType(requestForm: any) {
if (
requestForm.goAddress != "" &&
requestForm.comeAddress == ""
) {
return "Outbound";
} else if (
requestForm.goAddress == "" &&
requestForm.comeAddress != ""
) {
return "Inbound";
} else if (
requestForm.goAddress != "" &&
requestForm.comeAddress != ""
) {
return "Both";
} else {
return "Your Request Selection Is Shown Here";
}
}
}

问题原因与解决方法

  • 核心问题:mat-fab按钮不属于表单控件,它没有实现ControlValueAccessor接口,无法通过formControlName绑定到Angular表单控件。Angular尝试调用该控件的writeValue方法时找不到对应实现,因此抛出错误。
  • 解决步骤:
    1. 移除按钮上的formControlName="TypeSelected"属性,按钮仅用于展示内容,不需要绑定表单控件。
    2. 在TS代码中监听表单值变化,主动将计算结果存入TypeSelected控件:
      export class RequestBusComponent implements OnInit {
        requestForm: FormGroup;
      
        ngOnInit() {
          // 初始化表单,包含所需控件
          this.requestForm = new FormGroup({
            goAddress: new FormControl(''),
            comeAddress: new FormControl(''),
            TypeSelected: new FormControl('')
          });
      
          // 监听地址字段变化,自动更新TypeSelected的值
          this.requestForm.valueChanges.subscribe(formValue => {
            const typeResult = this.selectedRequestType(formValue);
            this.requestForm.get('TypeSelected')?.setValue(typeResult);
          });
        }
      
        selectedRequestType(requestForm: any) {
          if (requestForm.goAddress !== "" && requestForm.comeAddress === "") {
            return "Outbound";
          } else if (requestForm.goAddress === "" && requestForm.comeAddress !== "") {
            return "Inbound";
          } else if (requestForm.goAddress !== "" && requestForm.comeAddress !== "") {
            return "Both";
          } else {
            return "Your Request Selection Is Shown Here";
          }
        }
      }
      
    3. 调整后HTML仅保留展示逻辑:
      <div>
        <button mat-fab color="primary" disabled>   
          {{selectedRequestType(requestForm.value)}}
        </button>
      </div>
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:54:22