Angular 7-多个下拉菜单选择更改

时间:2019-01-13 13:20:40

标签: angular angular2-forms ngrx ngrx-store

我有一个表单数组,该数组由带有brandmodel的formGroup组成。

组件:

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>

brandmodel是一个下拉列表。我显示了基于所选品牌的型号列表,我对品牌selectionChange进行了操作,以获取型号列表。

由于该模型是我已订阅的Observable。当我在表单数组中只有一项时,一切正常。当我在品牌selectionChange上添加另一个组时,可观察到的model会更新为最新数据,而第一个model中的group将变为空白,因为选择了其他品牌来自第二组。

在使用NGRX时如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

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

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

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