如何将函数调用结果存入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方法时找不到对应实现,因此抛出错误。 - 解决步骤:
- 移除按钮上的
formControlName="TypeSelected"属性,按钮仅用于展示内容,不需要绑定表单控件。 - 在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"; } } } - 调整后HTML仅保留展示逻辑:
<div> <button mat-fab color="primary" disabled> {{selectedRequestType(requestForm.value)}} </button> </div>
- 移除按钮上的
内容的提问来源于stack exchange,提问作者Deviously Unknown
相关产品推荐
相关产品推荐

