Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

typescript - How to fetch value of a Dropdown option in Angular form

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.

question from:https://stackoverflow.com/questions/65644652/how-to-fetch-value-of-a-dropdown-option-in-angular-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...