Home > OS >  How to add validation in nested form array?
How to add validation in nested form array?

Time:06-03

I have a problem on validation on calculation. The total quota should be sum of each quota. However, this total quota should be input by user (not calculation). If all quota are sum and also not same value as total quota, it will trigger a validation when user click save button. As I can't find any solution in form array validation, is it able to implement on it?

Here's a StackBlitz: enter link description here

CodePudding user response:

You can use the below code to validate the quota.

checkTotal() {
 this.sessionListessionDynamicForm.value.sessionList.forEach((session, index) => {
   let sum = 0;
   session.enrolTypeList.forEach((list) => {
     sum  =  list.subQuota;
   });
   if(sum != session.totalQuota){
     console.log('session',index 1, 'has mismatch')
     //add setError code here
   }
 });
}

You can add errors to the sessions having mismatch using setError by adding code at marked position in code

CodePudding user response:

Your inner formArray is valid if the quotes sum a value that belong to the formGroup. So you need validate the formGroup, not the formArray

this.data.sessionList.forEach((x) => {
  this.sessionListFormArr.push(
    this.fb.group(
      {
        sessionId: x.sessionId,
        totalQuota: x.totalQuota,
        enrolTypeList: this.setenrolTypeList(x),
      },
      
      { validator: this.checkTotlalQuotaValidator() }
    )
  );
});

And the custom validator is simply

  checkTotlalQuotaValidator(form: FormGroup) {
    const totalQuota: number =  form.get('totalQuota').value;
    const subQuota:any[]= form.get('enrolTypeList').value;
    const sumSubquota=subQuota.reduce((a,b)=>a b.subQuota,0)

    return sumSubquota==totalQuota?null:{error:'should meet the sum'}
  }

Now you can use this error in your .html like

   <div  style="color:blue">
                        Total Quota: {{sessionListFormArr.controls[i].errors|json}}
   </div>

And

<button [disabled]="sessionListessionDynamicForm.invalid" 
      (click)="checkTotal()">save</button>

Well, a Validator is executed by defect each time the FormControl or the FormGroup change, so Angular execute severals time the function. You can indicate that this is executed only on submit -in this case you can not use [disabled] in the button-

{ validators: [this.checkTotlalQuotaValidator],updateOn:'submit' }

NOTE: You should use form -no <div> when you has a Form and the button should be inside the "form"

  • Related