I have been working with Angular 11 to create dynamic form inputs and I am facing a challenge with validating the form fields that are added dynamically when clicking the "add" button. I have tried multiple solutions but haven't found the right one yet. Below is a snippet of my code:
Component.ts file
this.pollAdd = this.fb.group({
question: ['',Validators.required],
queChoices:this.fb.array([this.createChoice()]),
});
addChoice(){
this.queChoices=this.pollAdd.get('queChoices') as FormArray;
this.queChoices.push(this.createChoice());
}
createChoice():FormGroup{
return this.fb.group({
choice:['',Validators.required],
})
}
get f() { return this.pollAdd.controls; }
In Component.html file
<div formArrayName="queChoices" *ngFor="let choices of pollAdd.get('queChoices')['controls'];let i=index;">
<mat-form-field class="ch__custom_input w-100 mt-3" [formGroupName]="i">
<mat-label>Choice {{i+1}}</mat-label>
<input matInput formControlName="choice" autofocus/>
</mat-form-field>
</div>
Could someone please guide me on how to validate each choice field in this scenario?