Home > Back-end >  How to assign formGroup to an array for form validation
How to assign formGroup to an array for form validation

Time:09-20

I have a repeater section in angular, i followed the below method to achive it, but i want to validate the form (Enable or disable the final submit button based on the validation),Here is the sample code.

ts file:-

      private formBuilder : FormBuilder
) { }
 
formInfoHolder = [];

onAdd(){
    let newForm = {
         let newForm = {
    subText : new FormControl('',[Validators.required,Validators.maxLength(250)]),
    header : new FormControl('',[Validators.required,Validators.maxLength(20)]),
    link : new FormControl('',[Validators.required,Validators.pattern('[a-zA-Z]*')]),  
}
        
    }
    this.formInfoHolder.push(this.formBuilder.group(newForm))
}
delete(toDelete){
    let del : any[] = [];
    for(let form of this.formInfoHolder){
       if(toDelete !== form){
            del.push(form);
       }
    }
    this.formInfoHolder = del;
}

then in HTML Component

<div *ngFor="let form of formInfoHolder">
     <form [formGroup]="form">
         <label for="username"> Username </label>
         <input id="username" type="text" formControlName="username">
         <!-- insert other input elements with the formControlName -->
         <label for="delete"> Delete </label>
         <input id="delete" type="button" (click)="delete(form)">
     </form>
</div>
<button (click)="onAdd()">Add</button>
<button [disabled]="//Here i want to validate" (click)="saveInfo()">Save</button>

How do i validate the form(enable the button only if all the fields are filled) which is stored in an array.

CodePudding user response:

Here is a Stackblitz example for what you are looking for I have used formarray and added formgroups into it, adding and removing formgroups becomes easy in formarray. Also validation also becomes easy because I only have check if the main form in valid

  • Related