Angular响应式表单中如何获取自定义下拉菜单的选中值
解决方法
你当前给非表单控件的div元素添加formControlName是无法生效的,你可以通过手动监听下拉选项的点击事件,给docid对应的FormControl赋值,具体修改如下:
1. 修改模板文件
- 移除dropdown div上的
formControlName="docid" - 给每个下拉选项绑定点击事件,选中时更新表单值,同时同步修改下拉按钮的显示文本
修改后的模板代码:
<form style="margin-left: 550px; margin-top: 100px;" [formGroup]='patientForm' (submit)='onPatientFormSubmit()'> <div class="row"> <div class="col-md-6"> <h1>Add Patient</h1> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Patient Name</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="name" formControlName="name"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">City</label> <input type="text" class="form-control" id="exampleInputCity1" placeholder="City" formControlName="city"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Illness</label> <input type="text" class="form-control" id="exampleInputIllness1" placeholder="Illness" formControlName="illness"> </div> <div class="dropdown mt-4"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> {{ selectedDoctor || 'Select Doctor' }} </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> <li><a class="dropdown-item" (click)="onDoctorSelect('action')">action</a></li> <li><a class="dropdown-item" (click)="onDoctorSelect('Another action')">Another action</a></li> <li><a class="dropdown-item" (click)="onDoctorSelect('Something else here')">Something else here</a></li> </ul> </div> <button type="submit" class="btn btn-primary mt-3">Submit</button> </div> </div> </form>
2. 修改component.ts文件
添加选中医生的处理方法,同时新增selectedDoctor变量用来存储选中的医生展示文本:
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-add-patient', templateUrl: './add-patient.component.html', styleUrls: ['./add-patient.component.css'] }) export class AddPatientComponent implements OnInit { patientForm: FormGroup; selectedDoctor: string = ''; constructor() { } ngOnInit(): void { this.patientForm = new FormGroup({ name: new FormControl('', [Validators.required, Validators.maxLength(20)]), city: new FormControl('', [Validators.required, Validators.maxLength(20)]), illness: new FormControl('', [Validators.required, Validators.maxLength(20)]), docid: new FormControl('', [Validators.required, Validators.maxLength(20)]), }); } onDoctorSelect(doctorVal: string) { this.selectedDoctor = doctorVal; // 手动给docid的表单控件赋值 this.patientForm.get('docid')?.setValue(doctorVal); } public onPatientFormSubmit(){ console.log(this.patientForm.value); // 这里直接取patientForm.value就包含docid字段,直接传给POST接口即可 } }
修改完成后点击下拉选项会自动给docid对应的表单控件赋值,提交表单时打印的patientForm.value就会包含下拉选中的值,不需要额外处理就可以和其他字段一起提交给后端接口。
内容的提问来源于stack exchange,提问作者Subhajit
相关产品推荐
相关产品推荐

