Reputation: 1499
I have checked many Stackblitz examples for formArray validations and disabled formControl based on the other formControl value and tried with the same approach but in my form it is not applying the same thing.
Validation on the qty
formControl is not working and if user select a value active from selection then fromControl qty
should be enabled otherwise it should be disabled by default that is also not working properly.
What the thing i am missing ?
Here is my Stackblitz demo.
Reference which i have used for validation. https://stackblitz.com/edit/angular-validate-dynamic-formarray-formbuilder-pru78n?file=app/app.component.ts
HTML component
<div formArrayName="dataCollection">
<div class="row" [formGroupName]="i" *ngFor="let element of data; let first = first; let i = index">
<div *ngIf="!first">----------</div>
<div formArrayName="sizes">
<ng-container [formGroupName]="j" *ngFor="let qtys of data[0].sizes; let j = index">
<div class="col">
<mat-form-field class="">
<input matInput type="text" formControlName="qty">
<!-- <p *ngIf="element['controls'].qty?.errors?.required">Qty is required</p>
<p *ngIf="element['controls'].qty?.errors?.pattern">Error pattern</p> -->
</mat-form-field>
<mat-form-field class="">
<mat-select placeholder="Status"
formControlName="statusMethod"
(selectionChange)="onSelectionChanged($event)">
<mat-option value="AC">Active</mat-option>
<mat-option value="IN">Deactive</mat-option>
</mat-select>
</mat-form-field>
</div>
</ng-container>
</div>
</div>
</div>
TS Component
onSelectionChanged({value}) {
if (value === 'IN') {
this.dataForm.get('dataCollection').get('qty').disable();
} else {
this.dataForm.get('dataCollection').get('qty').enable();
}
}
Upvotes: 0
Views: 1369
Reputation: 1227
In your onSelctionChanged()
method there are no references to the selected FormArray indices. You must pass them from the template like (selectionChanged)="onSelectionChanged(i, j)"
.
Now you can use the indices to access your data in the nested FormArrays:
onSelectionChanged(i, j) {
const control = (<FormArray>((<FormArray>this.dataForm.get("dataCollection")).at(i).get("sizes"))).at(j);
if (control.get("statusMethod").value === "IN") {
control.get("qty").disable();
} else {
control.get("qty").enable();
}
}
Further information about accessing data in FormArray can be found in the documentation or in this entry.
Here is the updated version of your Stackblitz Demo.
Upvotes: 1