Angular表单数组报错:找不到路径'instructions->1->action'的控件
问题原因
你点击添加按钮时,往instructions表单数组中添加的是普通FormControl(this.fb.control("")),但模板中每个数组项对应的是包含action和data的FormGroup,结构不匹配导致Angular找不到action控件,从而抛出错误。
解决步骤
- 封装单个指令的表单组创建逻辑
新增私有方法生成符合结构的指令表单组,避免重复代码:
private createInstructionGroup(): FormGroup { return this.fb.group({ action: this.fb.control('', Validators.required), data: this.fb.group({ message: this.fb.control(""), mediaName: this.fb.control(""), mediaType: this.fb.control(""), commandName: this.fb.control(""), commandTrigger: this.fb.control("") }) }); }
- 修改表单初始化代码
用上述方法替换原硬编码的默认指令项:
this.buttonForm = this.fb.group({ instructions: this.fb.array([ this.createInstructionGroup() ]), name: this.fb.control("", Validators.required), dimensions: this.fb.group({ width: this.fb.control(5, [Validators.required, Validators.min(1)]), height: this.fb.control(5, [Validators.required, Validators.min(1)]), positionX: this.fb.control(5, [Validators.required, Validators.min(0)]), positionY: this.fb.control(5, [Validators.required, Validators.min(0)]) }) });
- 修正添加指令的方法
把添加普通FormControl的逻辑改成添加正确的FormGroup:
public addInstruction() { this.instructionAray.push(this.createInstructionGroup()); }
- 可选:修正拼写规范
你的getter方法拼写有误(instructionAray),建议修正为instructionArray,同时同步修改模板中的对应引用:
get instructionArray() { return this.buttonForm.get("instructions") as FormArray; }
模板中把*ngFor="let instruction of instructionAray.controls"改成*ngFor="let instruction of instructionArray.controls"。
内容的提问来源于stack exchange,提问作者Mytho
相关产品推荐
相关产品推荐

