Martin
Martin

Reputation: 557

Fetching Selected value from a dropdown list in Angular 8

Am working on a Single Page Application using Angular 8 on the frontend and Laravel on the backend. I have got a form which has input text field and a dropdown list. The values on the text input fields are being captured well on the typescript file but am having a problem capturing the value selected from the drop down list so that I can submit on the backend..

~ Kindly assist?

Create.component.html

<form #createForm=ngForm (ngSubmit)="onSubmit()">
    <div class="form-group row">
     <div class="col-sm-6">
        <label for="formGroupExampleInput">Child SurName</label>
        <input 
            type="text" 
            name="childSurName" 
            class="form-control" 
            id="childSurName" 
            placeholder="ChildSurName"
            [(ngModel)]="form.childSurName">
    </div>

    <div class="col-sm-6">
        <label for="child-gender">Child Gender</label>
        <select class="form-control" id="childGender" name="child-gender" required>
        <option value="" selected disabled> Child's Gender</option>
            <option value="Male"> Male</option>
            <option value="Female"> Female </option>
        </select>
    </div>
    </div>

    <div class="form-group row">
        <div class="col-sm-12">
            <button 
                type="submit" 
                class="btn btn-lg btn-success btn-block" 
                [disabled]="!createForm.valid">Save Details </button>
        </div>
    </div>
</form>

Create.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/Services/auth.service';
import { Router } from '@angular/router';
import { AuthCheckService } from 'src/app/Services/auth-check.service';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})

export class CreateComponent implements OnInit {

  public form = {
    childSurName: null,
    child-gender: null
  };

  public error = null;

  constructor(
       private Auth:AuthService,
       private router: Router,
       private AuthCheck : AuthCheckService) 
  { }

   //Submit form data to the backend via a function in he service file
   onSubmit(){
    this.Auth.submitFormData(this.form).subscribe(
      data => console.log(data),
      error => console.log(error)
    );
  }

  ngOnInit() {
  }

}

Upvotes: 3

Views: 21626

Answers (2)

Nicholas K
Nicholas K

Reputation: 15423

Add the following to the <select>

[(ngModel)]="form.childGender"

Also for consistency rename the key of your form to:

public form = {
   childSurName: null,
   childGender: null
};

Here's a working stackblitz for the same. (Note that on submit only the form is being logged to the console)

Upvotes: 1

kiranghule27
kiranghule27

Reputation: 443

[(ngModel)] directive seems to be missing on your select element.

Upvotes: 3

Related Questions