Angular响应式表单报错:对象可能为null、controls属性不存在
Angular响应式表单的TypeScript编译错误解决办法
出现的编译错误
- TS2531: Object is possibly 'null'
- 元素隐式拥有'any'类型,因为类型为"controls"的表达式无法用于索引AbstractControl<any, any>类型,该类型不存在'controls'属性
错误原因
- TS2531错误:
reactiveForm.get('skills')的返回类型是AbstractControl | null,TypeScript严格模式下不允许直接访问可能为null的对象属性。 - 隐式any类型错误:
get()方法返回的AbstractControl基类没有controls属性,只有FormArray才有。直接访问['controls']时,TypeScript无法确定返回的是FormArray,因此报错。
解决步骤
1. 组件中添加FormArray获取方法
在TS组件类里新增一个getter方法,专门获取skills对应的FormArray,同时通过类型断言明确返回类型,解决null和类型不确定的问题:
get skillsFormArray(): FormArray { return this.reactiveForm.get('skills') as FormArray; }
2. 修改HTML模板代码
把模板中直接访问reactiveForm.get('skills')['controls']的部分,替换成我们定义的skillsFormArray.controls,同时给input绑定对应的表单控件:
<div class="form-group" formArrayName="skills"> <ng-container *ngFor="let skill of skillsFormArray.controls; let i = index;"> <label for="Skills-{{i}}">Skills {{i+1}}</label> <input type="text" [formControlName]="i"> </ng-container> </div>
完整组件TS代码
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms'; @Component({ selector: 'app-your-component', // 替换为你的组件选择器 templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { reactiveForm!: FormGroup; ngOnInit(): void { this.reactiveForm = new FormGroup({ firstname: new FormControl(null, Validators.minLength(4)), lastname: new FormControl(null, Validators.required), email: new FormControl('patelchintan843@gmail.com', [Validators.required, Validators.email]), country: new FormControl('Canada'), gender: new FormControl('male'), hobbies: new FormControl(null), skills: new FormArray([ new FormControl(null), ]) }); } get skillsFormArray(): FormArray { return this.reactiveForm.get('skills') as FormArray; } onSubmit() { console.log(this.reactiveForm); } }
内容的提问来源于stack exchange,提问作者CHINTAN PATEL
相关产品推荐
相关产品推荐

