无法使用 Angular Reactive Forms 将选择选项的值设置为 ngFor 循环中的第一个元素

问题描述 投票:0回答:1

我有一个带有 ngFor 循环的选择输入,用于根据颜色数组创建选项。

我需要的行为是自动选择第一个选项,以便角度反应形式可以在创建/更改输入时获取其值。

到目前为止我的表格看起来像这样:

<form [formGroup]="stepOneForm">
  <label for="modelSelect">Model:</label>
  <select id="modelSelect" formControlName="model">
    <option value="" selected>Choose...</option>
    <option *ngFor="let model of models" [value]="model.code">
      {{ model.description }}
    </option>
  </select>

  <!-- The input i am interested in -->
  <ng-container *ngIf="stepOneForm.get('model')?.value as code">
    <label for="colorSelect">Color:</label>
    <select id="colorSelect" formControlName="color" (change)="onColorSelected()" [value]="colors[0].code">
      <option *ngFor="let color of colors" [value]="color.code">
        {{ color.description }}
      </option>
    </select>
    <img [src]="imagePath" alt="car">
  </ng-container>
</form>

我的 TS 部分如下所示:

ngOnInit() {
    this.carService.getModels().subscribe(models => {
      this.models = models;
    });

    this.stepOneForm.valueChanges.subscribe(() => {
      this.carService.updateStepOneValidity(this.stepOneForm.valid);
      const model = this.stepOneForm.get('model')?.value
      this.colors = this.models.find(modelObj => modelObj.code === model)?.colors ?? [];
      
      console.log(this.stepOneForm.get('color')?.value) // This returns '' (empty string)
      
      if (model) {
        this.carService.updateShoppingCart(this.stepOneForm.value)
      }
    })
  }

当显示 ng-container 内容时,订阅被触发,并且在颜色输入上我看到默认选择的颜色,但在这一行我得到一个空字符串,而我应该获取此选项的值:

console.log(this.stepOneForm.get('color')?.value)

angular typescript angular-reactive-forms
1个回答
0
投票

它只是更新视图,但要以编程方式更新表单控件值,必须使用组件中的表单方法来完成,使用

.setValue/.patchValue

因此,您可以向第一个选择添加侦听器,然后更新颜色表单控件。

<select id="modelSelect" formControlName="model" (change)="onModelSelected()">
  onModelSelected() {
    this.stepOneForm.get('color').setValue(this.colors[0]?.code || '');
  }
© www.soinside.com 2019 - 2024. All rights reserved.