Angular 4 - 依赖值表单选择

时间:2018-01-29 17:31:06

标签: angular angular-material2

我的数据结构如下:

cars = [
    {name: 'Ferrari', models:['LaFerrari', 'Enzo', 'F40'],
    {name: 'Lamborghini', models:['Aventador', 'Diablo', 'Gallardo']
]

我正在使用Angular Material作为我的表单ui,它看起来像:

<form [formGroup]="carsForm">
  <button mat-button color="primary" (click)="addChoice()">Add Car</button>
    <div formArrayName="carChoices">
      <div *ngFor="let choice of carChoices.controls; index as i">
        <div [formGroupName]="i">
          <mat-form-field>
            <mat-select placeholder="Manufacturer" [(ngModel)]="selectedValue" formControlName="manufacturer">
            <mat-option *ngFor="let car of cars" [value]="car">
              {{car.name}}
            </mat-option>
          </mat-select>
        </mat-form-field>
        <mat-form-field *ngIf="selectedValue">
          <mat-select placeholder="Model" formControlName="model">
          <mat-option *ngFor="let model of selectedValue.models" [value]="model">
            {{model}}
          </mat-option>
          </mat-select>
        </mat-form-field>
      </div>
    </div>
  </div>
</form>

这是我的组件类的摘录:

export class SelectFormExample {

    carsForm: FormGroup;

    constructor(private fb: FormBuilder) {this.initializeForm()}

    cars = [
      {name: 'Ferrari', models: ['LaFerrari', 'Enzo', 'F40']},
      {name: 'Lamborghini', models: ['Aventador', 'Diablo', 'Gallardo']}
    ];

    get carChoices() {
      return this.carsForm.get('carChoices') as FormArray;
    }

    initializeForm() {
      this.carsForm = this.fb.group({
        carChoices: this.fb.array([this.initializeChoices()])
      })
    }

    initializeChoices() {
      return this.fb.group({
        manufacturer: [''],
        model: ['']
      })
    }

    addChoice() {
      this.carChoices.insert(0, this.initializeChoices());
    }

}

如何根据选择的汽车来填充模型下拉字段?

我尝试在制造商mat-select字段上使用[(ngValue)],但问题是表单上有一个选项可以添加另一辆车,当添加另一辆车时,它会自动填充上一个选择的值。

编辑:这是一个stackblitz,显示了我想要实现的目标 - https://stackblitz.com/edit/angular-9y72pr - 这里的问题是我只需要car.name作为我的表单模型,当更多的汽车是添加到formGroup。

这是一个更完整的stackblitz,显示使用多个formGroup时的问题 - https://stackblitz.com/edit/angular-9y72pr-sjh8uh

0 个答案:

没有答案