I am working with a Reactive form. I have 2 sets of data. They are:
Here is what I am trying to do:
SUMMARY OF THE ISSUE:
I am trying to assign a Group to each of those Items. So I am trying to fix the (above) connected behavior of the forms, so that each form should work independently of the other in the loop and after selecting a Group, when the "Assign Group" button is clicked, I am trying to access the corresponding Item ID and Group ID of only the form that was submitted and not the other forms. How can this be achieved with proper Validation/Errors showing up for the submitted forms, as and when they are accessed?
LIVE DEMO OF THE ISSUE:
I have already setup a StackBlitz demo here replicating the issue.
LIVE DEMO EDITOR CODE:
Here is the Live Demo Editor code
actually with your code angular understand that there's one Form (formControlName) called: partnerGroupsId so all of them are linked with same ID and name
LIVE SOLUTION : https://angular-2-accessing-reactive-forms-independently.stackblitz.io
LIVE EDIT CODE : https://stackblitz.com/edit/angular-2-accessing-reactive-forms-independently
SOLUTION :
You need to loop through your data (this.allData) to build form Builder groups :
const groups = {};
for(let i = 0; i< this.allData.length; i++) {
groups['partnerGroupsId' + i] = ['', [
Validators.required,
]];
}
this.applicationForm = this.formBuilder.group(
groups
);
and use the below HTML :
<ul class="pb-0">
<ng-container *ngFor="let item of allData; let i = index">
<li>
<label class="label">
{{item.item_name}} /
<span class="label-heading">Item ID # {{item.item_id}}</span>
</label>
<form [formGroup]="applicationForm" (ngSubmit)="assignGroup()"
(keyup.enter)="assignGroup()"
class="full-width">
<label position="floating">Select Group</label>
<select formControlName="partnerGroupsId{{ i }}">
<option value="">Select a Group from this list</option>
<option *ngFor="let partnerGroups of allDataGroups;"
value="{{partnerGroups.group_id}}" selected>
{{partnerGroups.display_name}}
</option>
</select>
<div class="validaterrors">
<ng-container *ngFor="let validation of validationMessages.partnerGroupsId;" >
<div class="error-message"
*ngIf="applicationForm.get('partnerGroupsId' + i).hasError(validation.type) && (applicationForm.get('partnerGroupsId' + i).dirty || applicationForm.get('partnerGroupsId' + i).touched)">
{{ validation.message }}
</div>
</ng-container>
</div>
<button color="primary" expand="block" type="submit" class="">
Assign Group
</button>
</form>
</li>
</ng-container>