I have a form array, the array consists of formGroup with brand
and model
.
Component:
get brands() {
return this.form.get('groups') as FormArray;
}
addGroup() {
this.groups.push(
this.fb.group({
brand: ['', Validators.required],
model: ['', Validators.required]
})
);
}
removeGroup(index: number) {
this.models.removeAt(index);
}
brandSelect(event: any) {
// I dispatch an action to get the models from the smart component
this.selectedBrand.emit(event);
}
HTML:
<ng-container formArrayName="groups" *ngIf="groups">
<div>
<a href="javascript:void(0)" (click)="addGroup()">
<small>
<i class="fas fa-plus-circle fa-fw margin-xs-r"></i> Add Group
</small>
</a>
</div>
<div *ngFor="let control of groups.controls; index as i">
<div class="text-right margin-sm-b">
<a (click)="removeGroup(i)"> <i class="fas fa-times fa-fw"></i> </a>
</div>
<ng-container [formGroupName]="i">
<mat-form-field appearance="outline">
<mat-label>Brand</mat-label>
<!--Based on the brand selected I dispatch an action to get the models.-->
<mat-select
formControlName="brand"
(selectionChange)="brandSelect($event)"
>
<mat-option *ngFor="let brand of brands" [value]="brand">
{{ brand | titlecase }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Model</mat-label>
<mat-select formControlName="model">
<mat-option *ngFor="let model of models" [value]="model">
<i class="fas fa-angle-right fa-fw margin-xs-r"></i> {{ model }}
</mat-option>
</mat-select>
</mat-form-field>
</ng-container>
</div>
</ng-container>
brand
and model
is a dropdown. I show the list of models based on the brand selected, I dispatch an action on brand selectionChange
to get the list of models.
As the model is an Observable which I've subscribed to. Everything works fine when I have only one item in the form array. The moment I add another group, on brand selectionChange
the model
observable gets updated with the latest data and the model
in the first group
goes blank because a different brand was selected from the second group.
How can I handle this situation while I'm using NGRX?
Unknown User, you need severals "models". For this, you can make that models was an object.
The idea is that,e.g., models was
models={
"seat":["ibiza","leon","panda"],
"kia":["cerato","ceed"]
}
And you iterate over models[brand]
<mat-option *ngFor="let model of models[brand]" [value]="model">
<i class="fas fa-angle-right fa-fw margin-xs-r"></i> {{ model }}
</mat-option>
So, define at first your models as
models:any={}
And, when change the brand fill
models[brand]=....an array of the list of models of this brand