问题
In one of my requirements, I have form an array-like grid table contains rows and columns. once on Init i am doing a service call and get the columns and values and error messages. based on that i have created a form array for that columns and each columns have errormessage if errormessage exists need to set errors.
I can able to set value for those columns but not able to set errors while pushing into form array i don't know how could I push error as well. stuck on this line.
Qn? On initially how we could set the errors in form array controls based on service response error messages i can able to see lots of demo only for set the value initially and set the validators for that controls.
But in my case i need to set error and set a value basedon server response.
eg) response is
[
{fieldName:'productId',fieldValue:'123',errorMessage:'Product Id should be alphanumeric'},
{fieldName:'productname',fieldValue:'123',errorMessage:'Product name should be 10 characters'}],
etc
onInit(){
// do the service call and get values once get values to push into formArray.But how could push the error as well.
Value is working fine
let result= service response;
result.forEach((item:any[], index) => {
let formData =this.formBuilder.group({
item.fieldName:[item.fieldValue],
item.fieldName:[item.fieldValue]
});
this.formArr.push(formData);
});
}
回答1:
The recommended approach is the use of updateValueAndValidity();
formData.updateValueAndValidity();
But there are some cautions that need to be understood.
these work fine on a individual formControl level.
But on a formGroup and formArray level, it'll only update the validity of its ancestors. Those are already detailed here Angular 6, this.formGroup.updateValueAndValidity() not working properly and Angular 6, this.formGroup.updateValueAndValidity() not working properly
The workaround for that is slightly odd but you could iterate and make this happen on these lines.
Object.keys(this.form.controls).forEach(key => { this.form.controls[key].updateValueAndValidity(); });
回答2:
You can simply call formData.setErrors({errorMessage:item.errorMessage}) before pushing to formArr.
来源:https://stackoverflow.com/questions/63888311/how-can-we-set-errors-on-form-array-control-dynamically-on-initally-page-load