mat-radio-group报NG01203错误,已用NG_VALUE_ACCESSOR仍未解决求助
问题:Angular响应式表单单元测试报错NG01203:No value accessor for form control name: 'gender'
单元测试失败,提示错误:NG01203: No value accessor for form control name : 'gender'。已配置NG_VALUE_ACCESSOR但问题依旧,当前使用Angular响应式表单,相关代码如下:
HTML代码
<mat-radio-group aria-label="Select an option" class="w-48" id="gender" name="gender" formControlName="gender" > <mat-radio-button value="Male" name="male">Male</mat-radio-button> <mat-radio-button value="Female" name="female">Female</mat-radio-button> </mat-radio-group>
组件配置代码
{ provide: NG_VALUE_ACCESSOR, useExisting: myComponent, multi: true }
请问哪里操作有误?
问题原因与解决方法
核心错误原因
你错误地给自定义组件myComponent配置了NG_VALUE_ACCESSOR注入令牌,但mat-radio-group本身已经由Angular Material实现了ControlValueAccessor接口,完全支持响应式表单的formControlName绑定。额外添加的NG_VALUE_ACCESSOR配置会干扰Angular对原生(Material封装的)表单控件的识别逻辑,导致找不到正确的值访问器。
具体解决步骤
移除多余的
NG_VALUE_ACCESSOR配置
直接删除组件providers数组中那项关于NG_VALUE_ACCESSOR的配置代码。确认模块导入依赖
确保你的应用模块(或特性模块)已经导入了MatRadioModule和ReactiveFormsModule:import { MatRadioModule } from '@angular/material/radio'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ // ...其他模块 ReactiveFormsModule, MatRadioModule ] }) export class YourModule { }单元测试模块补全依赖
在单元测试的TestBed配置中,必须导入MatRadioModule和ReactiveFormsModule,否则测试环境无法识别Material控件和响应式表单指令:beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ ReactiveFormsModule, MatRadioModule ], declarations: [myComponent] }).compileComponents(); });
完成以上步骤后,重新运行单元测试,即可解决NG01203报错问题。
内容的提问来源于stack exchange,提问作者user17449555
相关产品推荐
相关产品推荐

