Search code examples
angularradio-buttonangular-ngmodel

What would be the radio equivalent of this ngModel text input form, using spring boot mvc and angular?


I was taking a tutorial on making an employee CRUD model that uses spring boot and mysql server for the backend and angular for the front end. On the Create part it had this form-group (the gender part I was adding new fields).

    <div class="form-group">
            <label>
                Gender </label>
            <input type="text" class="form-control" id="gender" required [(ngModel)]="employee.gender" name="gender">
        </div>

And that would work when submitting it (ie. creating the employee). But I can't figure out how to turn it into a radio button and submit it (it just gets stuck on the create page). This is what I tried to make when following a radio button example.

<div class="form-group">

            <label for [(ngModel)]="employee.gender">Gender:</label>
            <div>
                <input id="male" type="radio" value="male" name="gender" formControlName="gender">
                <label for="male">Male</label>
            </div>

            <div>
                <input id="female" type="radio" value="female" name="gender" formControlName="gender">
                <label for="female">Female</label>
            </div>
        </div>

My understanding could use more work, but I'm trying to learn. Any help is appreciated. Thanks


Solution

  • In Angular, there are two different approaches when it comes to working with Forms:

    In case of Template-driven forms we make use of ngModel for data binding, whereas in case of Reactive forms we work with FormControls.

    The 1st example shared in the question is using Template-driven approach, and the radio button equivalent code with two options to choose from, would be:

    <div class="form-group">
      <label>Gender:</label>
      <div>
        <input id="male" type="radio" value="male" name="gender" [(ngModel)]="employee.gender">
        <label for="male">Male</label>
      </div>
    
      <div>
        <input id="female" type="radio" value="female" name="gender" [(ngModel)]="employee.gender">
        <label for="female">Female</label>
      </div>
    </div>
    

    In case of Reactive forms approach, you can simply replace [(ngModel)]="employee.gender" with formControlName="gender" provided you have defined a FormControl named gender within your FormGroup.