【问题标题】:How to fetch select option text inside another input in Angular Reactive Forms如何在Angular Reactive Forms的另一个输入中获取选择选项文本
【发布时间】:2019-11-20 06:48:44
【问题描述】:

我的 Angular 反应式表单中有一个选择字段,我想提取用户选择的 <option> 标记内的文本值,然后在输入中动态填充其值(如更改事件)

COMPONENT.HTML

                   <div class="form-group">
                        <label>Select Plant</label>
                        <select class="form-control" formControlName="plantId" name="plantId" id="plantId">
                          <option [ngValue]="1">ABC</option>
                          <option [ngValue]="2">XYZ</option>  
                        </select>
                        <app-control-messages [control]="storlocForm.get('plantId')"></app-control-messages>
                    </div>
                    <div class="form-group">
                        <label>Plant Name *</label>
                        <input id="plantName" class="form-control" type="text" formControlName="plantName" name="plantName" value="" />
                    </div>

假设如果用户从下拉列表中选择 XYZ,我希望将值“XYZ”填充到以下输入(植物名称)中,而不是值“2”。

COMPONENT.TS

this.storlocForm = this.formBuilder.group({
      plantId: ['', Validators.required],
      plantName: ['']
    });
}

【问题讨论】:

    标签: angular onchange angular-reactive-forms angular-forms formgroups


    【解决方案1】:

    只需将更改事件添加到选择元素并更新表单控件,如下所示。

    <select class="form-control" formControlName="plantId" name="plantId" id="plantId" (change)="update($event)">
                     <option [ngValue]="1">ABC</option>
                              <option [ngValue]="2">XYZ</option>  
                    </select>
    
    update(event): void {
            let plantName = event.target.options[event.target.options.selectedIndex].text;
            this.form.controls.plantName.setValue(plantName);
        }
    

    【讨论】:

      【解决方案2】:

      您必须为数组使用键值对,因此用户 {key : "XYZ", value: "XYZ"},{key:"ABC", value: "ABC"}

      【讨论】:

      • 我没找到你
      • 我的意思是如果你不想通过下拉菜单获取,你可以使用相同的键值对
      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多