Angular自定义表单中下拉框选项值无法获取问题求助
experience Field in Angular Form Submission Hey there! Let's break down why your experience field is coming up empty when you submit the form, and how to fix it.
The Root Cause
The issue is the [ngModelOptions]="{standalone: true}" attribute on your <select> element. When you set standalone: true, Angular treats this form control as completely independent from the parent ngForm. That means it won't be included in the contactForm.value object you're trying to access in your onSubmit method—even though you've set up the #experience="ngModel" template reference.
Your email field works because it's registered properly with the form (it likely has a name attribute and isn't marked as standalone), so it shows up in contactForm.value.
Solution 1: Register the Control with the Form (Recommended)
This is the standard approach for template-driven forms. Remove the standalone option, add a name attribute to the select, and bind it to a property:
- Update your template's
<select>element:
<label class="label" for="experience">How did you find the booking experience?</label> <select id="experience" name="experience" <!-- Required for form registration --> #experience="ngModel" [(ngModel)]="selectedExperience" <!-- Bind to a component property --> > <option selected>Choose...</option> <option value="excellent">Excellent</option> <option value="verygood">Very good</option> <option value="good">Good</option> <option value="fair">Fair</option> <option value="poor">Poor</option> </select>
- Add the property to your component class:
selectedExperience: string = '';
Now the experience field will be included in contactForm.value, so your original onSubmit code will work as expected—email.experience will hold the selected value.
Solution 2: Keep Standalone but Access the Control Directly
If you need to keep the standalone setting (e.g., you don't want this field to affect form validity), you can pass the template reference directly to your onSubmit function and use its value:
- Modify the form's
ngSubmitevent to pass theexperiencecontrol:
<form (ngSubmit)="onSubmit(contactForm, experience)" #contactForm="ngForm">
- Update your
onSubmitmethod to use the control's value:
onSubmit(contactForm: NgForm, experience: NgModel) { console.log("called"); if (contactForm.valid) { const email = contactForm.value; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.post('https://formspree.io/f/xnqolzjd', { replyto: email.email, experience: experience.value // Use the standalone control's value directly }, { headers: headers } ).subscribe(response => { console.log(response); }); } }
Either solution will fix the empty experience field issue. Solution 1 is more aligned with Angular's template-driven form best practices, so it's the go-to choice unless you have a specific reason to keep the control standalone.
内容的提问来源于stack exchange,提问作者Tanzeel

