
在angular的响应式表单中,formarray是一个强大的工具,用于管理一个动态的表单控件集合,例如一个商品列表、一个联系人列表或本例中的一个特征列表。它允许我们在运行时添加、删除或重新排序表单控件组。然而,不正确的实现方式常常会导致运行时错误,其中最常见的就是typeerror: feature_r5.get is not a function。
这个错误通常发生在尝试在一个非AbstractControl对象上调用.get()方法时。在*ngFor循环中,如果迭代的是FormArray的value属性,那么循环变量feature将是一个普通的JavaScript对象,而不是一个FormGroup或FormControl实例。普通的JavaScript对象不具备.get()方法,因此会导致上述错误。
原始代码中导致TypeError的主要问题在于:
为了避免上述错误并正确实现动态表单,我们需要遵循以下几个关键点:
首先,在你的组件类中为FormArray创建一个getter方法。这样做有几个好处:它提高了代码的可读性,并确保我们在模板中始终访问的是FormArray的实际控件集合。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'app-post-adv',
templateUrl: './post-adv.component.html',
styleUrls: ['./post-adv.component.css']
})
export class PostAdvComponent implements OnInit {
advForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.advForm = this.fb.group({
// 其他表单控件...
features: this.fb.array([]) // 初始化为空的FormArray
});
}
// 为FormArray创建一个getter
get featuresFormArray(): FormArray {
return this.advForm.get('features') as FormArray;
}
// 添加特征按钮的点击事件
addFeatureButtonClick(): void {
this.featuresFormArray.push(this.createFeatureGroup());
}
// 创建一个新的特征FormGroup
createFeatureGroup(): FormGroup {
return this.fb.group({
fName: ['', Validators.required]
});
}
// 可选:移除特征
removeFeature(index: number): void {
this.featuresFormArray.removeAt(index);
}
}在模板中,*ngFor指令应该迭代FormArray的controls属性,而不是value属性。controls属性返回一个AbstractControl数组,其中每个元素都是一个FormGroup或FormControl实例,它们拥有.get()方法。
<!-- 错误示例:*ngFor="let feature of advForm.get('features')?.value" -->
<!-- 正确示例:-->
<div formArrayName="features">
<div *ngFor="let featureGroup of featuresFormArray.controls; let i = index" [formGroupName]="i">
<!-- 你的输入控件 -->
</div>
</div>formGroupName是一个指令,用于将FormArray中的每个FormGroup绑定到对应的HTML元素。它应该使用属性绑定[],而不是字符串插值或attr.绑定。
<!-- 错误示例:<div attr.formGroupName="{{i}}"> -->
<!-- 正确示例:-->
<div [formGroupName]="i">
<!-- 表单控件 -->
</div>在模板中访问表单控件的属性(如invalid、touched、errors)时,为了避免在控件可能为null或undefined时(例如在异步加载或初始化过程中)抛出错误,建议使用安全导航操作符?.。
<!-- 错误示例:feature.get('fName').invalid -->
<!-- 错误示例:feature.get('fName').errors.required -->
<!-- 正确示例:-->
<span class="help-block" *ngIf="featureGroup.get('fName')?.invalid && featureGroup.get('fName')?.touched">
Feature is required
</span>
<span class="help-block" *ngIf="featureGroup.get('fName')?.errors?.required && featureGroup.get('fName')?.touched">
Feature is required
</span>结合上述所有修正,以下是优化后的HTML模板代码:
<div id="features" class="tab-pane mytab-pane">
<div class="form-group">
<button type="button" class="btn btn-primary" (click)="addFeatureButtonClick()">Add</button>
</div>
<!-- formArrayName 应该在循环外部,包围整个 FormArray 区域 -->
<div formArrayName="features">
<!-- 迭代 FormArray 的 controls 属性,每个 featureGroup 都是一个 FormGroup 实例 -->
<div *ngFor="let featureGroup of featuresFormArray.controls; let i = index" [formGroupName]="i">
<!-- formGroupName 作为指令绑定 -->
<div class="form-group" [ngClass]="{'has-error' : featureGroup.get('fName')?.invalid &&
featureGroup.get('fName')?.touched}">
<div class="input-group">
<span class="input-group-prepend">
<label class="input-group-text"><strong>Features</strong></label>
</span>
<input type="text" id="{{'fName'+i}}" name="fName" class="form-control" placeholder="Features"
formControlName="fName"/>
</div>
<!-- 使用安全导航操作符处理错误检查 -->
<span class="help-block" *ngIf="featureGroup.get('fName')?.errors?.required &&
featureGroup.get('fName')?.touched">
Feature is required
</span>
<!-- 可选:添加一个删除按钮 -->
<button type="button" class="btn btn-danger btn-sm" (click)="removeFeature(i)">Remove</button>
</div>
</div>
</div>
</div>通过本文的讲解,我们可以看到,在Angular中正确使用FormArray构建动态表单需要注意以下几点:
遵循这些最佳实践,将有助于您在Angular应用中构建出更加健壮、易于维护的动态表单。
以上就是Angular动态表单中FormArray的正确使用与常见错误解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号