当使用FormArray来循环响应式表单时,可以使用以下解决方法来获取错误:
*ngFor
循环formArray.controls
来获取每个表单控件的错误信息。例如:
Field is required
Field should have at least 5 characters
get
方法获取表单控件的错误信息。例如:import { Component } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
myFormArray: FormArray;
constructor() {
this.myFormArray = new FormArray([
new FormGroup({
myControl: new FormControl('', [Validators.required, Validators.minLength(5)])
}),
new FormGroup({
myControl: new FormControl('', [Validators.required, Validators.minLength(5)])
})
]);
}
getControlErrors(control: FormControl) {
return control.errors;
}
}
在HTML模板中,使用getControlErrors
方法来获取控件的错误信息。例如:
Field is required
Field should have at least 5 characters
这些方法可以帮助你在使用FormArray循环时获取响应式表单的错误信息。