0

I'm creating a custom form. I've created a custom form:

<form (ngSubmit)="onSubmit(contactForm)" #contactForm="ngForm">
  ....email input filed
  <label class="label" for="experience">How did you find the booking experience?</label>
  <select id="experience" #experience="ngModel"[ngModelOptions]="{standalone: true}">
        <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>
    <button type="submit " value="Send ">Send</button>
</form>

here is the typescript:

  onSubmit(contactForm: NgForm) {
    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: email.experience },
        { 'headers': headers }).subscribe(
          response => {
            console.log(response);
          }
        );
    }
  }

But my experience: email.experience is blank in the object. It works when I hard code some value in the object itself. replyto: email.email is fetching correct value. Please help.

1 Answer 1

1

when we set ngModelOptions to standalone, it will not register with parent form, that's why you getting empty object. Try setting standalone to false and try

<form (ngSubmit)="onSubmit(contactForm)" #contactForm="ngForm">
  ....email input filed
  <label class="label" for="experience">How did you find the booking experience?</label>
  <select id="experience" name="experience" #experience="ngModel" [ngModelOptions]="{standalone: false}">
        <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>
    <button type="submit " value="Send ">Send</button>
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

What If just remove it instead of making it false. I added it because i was getting this error on console: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.
That's also fine for your refrence i have set false, yes you have to set name attribute on form control element.
Now I'll write unit test cases. We may want to re-open this discussion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.