How can we set errors on form array control dynamically on initally page load

北城余情 提交于 2021-01-29 10:33:46

问题


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.

  1. these work fine on a individual formControl level.

  2. 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

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!