在Angular 2+中,可以使用FormControl来创建具有验证的响应式表单。当在ngFor循环中使用时,可以为每个表单控件创建一个独立的FormControl对象。
以下是一个示例代码,展示如何在ngFor循环中独立访问具有验证的响应式表单:
在组件类中定义一个数组来存储表单控件:
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
formControls: FormControl[] = [];
constructor() {
// 在这里初始化表单控件数组
for (let i = 0; i < 5; i++) {
this.formControls.push(new FormControl('', Validators.required));
}
}
}
在模板中使用ngFor循环来创建表单控件:
在上述示例中,通过在组件类中循环创建FormControl对象并将其存储在formControls数组中。然后,在模板中使用ngFor循环来遍历formControls数组,并为每个表单控件创建一个独立的input元素。通过将FormControl对象绑定到input元素的[formControl]属性上,可以使表单控件与input元素进行关联。
在表单控件上使用control.invalid和control.errors来检查表单控件的验证状态,并根据需要显示错误消息。在示例中,当控件无效(invalid)且控件已被修改(dirty)或已触摸(touched)时,将显示错误消息。
这样,你就可以在ngFor循环中独立访问具有验证的响应式表单。