首页 > 解决方案 > Angular 7 - Multiple Dropdowns Selection Change

问题描述

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?

标签: angularangular2-formsngrxngrx-store

解决方案


未知用户,您需要多个“模型”。为此,您可以使模型成为一个对象。

这个想法是,例如,模型是

models={
   "seat":["ibiza","leon","panda"],
   "kia":["cerato","ceed"]
}

然后你迭代模型[品牌]

<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>

因此,首先将您的模型定义为

models:any={}

并且,当改变品牌填充

models[brand]=....an array of the list of models of this brand

推荐阅读