У меня есть массив форм, массив состоит из formGroup с brand
и model
.
Компонент:
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
и model
- это выпадающий список. Я показываю список моделей на основе выбранной марки, отправляю акцию на марку selectionChange
, чтобы получить список моделей.
Поскольку модель является Обсерваторией, на которую я подписан. Все отлично работает, когда у меня есть только один элемент в массиве формы. В тот момент, когда я добавляю другую группу, для бренда selectionChange
наблюдаемая model
обновляется с последними данными, и model
в первом group
становится пустым, поскольку во второй группе был выбран другой бренд.
Как мне справиться с этой ситуацией, когда я использую NGRX?