Radio Buttons in Angular Template Driven Forms

Radio Buttons in Angular Template Driven Forms

In this article, I am going to discuss Radio Buttons in Angular Template Driven Forms in detail. Please read our previous article as it is a continuation part to that article where we discussed Angular Template Driven Forms. At the end of this article, you will understand what are Radio Buttons and when and how to use Radio Buttons in Angular Template Driven Forms.

What is a Radio Button?

A Radio Button is an HTML element which is basically allows the user to select a single option from a predefined list of options. For example, you can create radio buttons for gender (Male and Female) and the user can only select either male radio button option or female radio button option but not the both.

Example to understand Radio Buttons in Angular Template Driven Forms:

Let us understand how to create and use Radio Buttons in Angular Template Driven Forms. We are going to work with the same example that we started in our previous article.

Now, we want to include the “Gender” radio buttons in the student registration form as shown in the below image. When we select student “Gender” using the radio buttons and when we click the “Submit” button, we want the selected gender value to be logged to the console.

Example to understand Radio Buttons in Angular Template Driven Forms

How to create radio button in angular template driven forms?

Please have a look at the below code which will create gender radio buttons with male and female options.

How to create radio button in angular template driven forms?

Code Explanation

In the above code, the name attribute of the input element radio is used to group the radio buttons as one unit which makes the selection mutually exclusive. The most important point that you need to keep in mind is that both the radio buttons should have the same value for the “name” attribute. Otherwise the radio button selection won’t be mutually exclusive.

Again if you notice we have set the value attribute of each radio button to make and female and this is the value which is going to be posted to the server when the form is submitted.

The complete code of app.component.html:

Following is the complete code of app.component.html file.

<br/>
<div class="container">
  <div class="row">
      <div class="form-bg">
          <form #studentForm="ngForm" (ngSubmit)="RegisterStudent(studentForm)"  >
            <div class="panel panel-primary">
              <div class="panel-heading">
                <h3 class="panel-title">Student Registration</h3>
              </div>

              <div class="panel-body">

                <div class="form-group">
                  <label for="firstName">First Name</label>
                  <input id="firstName" type="text" class="form-control"
                        name="firstName" ngModel>
                </div>

                <div class="form-group">
                  <label for="lastName">Last Name</label>
                  <input id="lastName" type="text" class="form-control"
                        name="lastName" ngModel>
                </div>

                <div class="form-group">
                  <label for="email">Email</label>
                  <input id="email" type="text" class="form-control"
                        name="email" ngModel>
                </div>

                <div class="form-group">
                  <label>Gender</label>
                  <div class="form-control">
                    <label class="radio-inline">
                      <input type="radio" name="gender" value="male" ngModel>
                      Male
                    </label>
                    <label class="radio-inline">
                      <input type="radio" name="gender" value="female" ngModel>
                      Female
                    </label>
                  </div>
                </div>

              </div>
              <div class="panel-footer">
                <button class="btn btn-primary" type="submit">Submit</button>
              </div>
            </div>
          </form>
      </div>
  </div>
</div>
Modifying the app.component.ts file:

We want to log the posted form values into the console. So, modify the app.component.ts file as shown below.

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms'

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

export class AppComponent {
  RegisterStudent(studentForm: NgForm): void {   

    // debugger;
    // var firstName = studentForm.controls.firstName.value;
    // var lastName = studentForm.controls.lastName.value;
    // var email = studentForm.controls.email.value;
    // var gender = studentForm.controls.gender.value;

    console.log(studentForm.value);
  }
}

With the above changes in place, now browse the application,open browser developers tool by pressing F12 key and open console tab. Then fill the form and click on the submit button and you should see the posted form values in the console tab as shown in the below image.

Radio Buttons in Angular Template Driven Forms

How to select a radio button checked by default in Angular?

As we know when working with real-time applications, sometimes we need to provide the one radio button to be checked by default when the form load initially and normally we can do this by adding the checked attribute of the radio button.

If you include the checked attribute to one of the radio buttons, then you may expect that the radio button to be checked by default. But in our example, you will not get that default checked. In our example, lets include the “checked” attribute on the “Male” radio button. So. Modify the gender HTML code as shown below.

<input type=”radio” name=”gender” value=”male” checked ngModel>

With the above changes now browse the application and you will see the Male radio button is not checked.

However, if you remove the “ngModel” directive from the radio button as shown below, then you will see that the Male radio button is checked when the form is load.

<input type=”radio” name=”gender” value=”male” checked>

In Angular Template Driven forms, we generally use the “ngModel” directive for two-way data binding. So when we put the ngModel directive back into the control then the “checked” attribute will not work as expected.

How to make it works?

In order to make it work include the “gender” property in the component class and initialize its value to the value of the radio button that you want to have checked by default. In our case, we want the “Male” radio button to be checked by default. So, we need to add “gender” property initialized to value of “male” in the component class as shown below.

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms'

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

export class AppComponent {
  gender = 'male';
  RegisterStudent(studentForm: NgForm): void {   
    console.log(studentForm.value);
  }
}
Modifying the app.component.html

Now modify the app.component.html file as shown below where we included the ngModel with gender property of the component class.

How to select a radio button checked by default in Angular?

At this point when you browse the application, you will see that the “Male” radio button is checked by default.

Now, if you remove the “checked” attribute from the “Male” radio button, then it is still checked by default when the form loads. This is possible because of the two-way data binding in angular. In our example, we do not want any radio button to be checked by default, so we remove the “checked” attribute and the “gender” property from the component class and ngModel directive.

How to disable a radio button in Angular Template Driven Forms?

In order to disable a radio button in Angular Template Driven Form, we need use the disabled attribute on that radio button. For example, if you want to make the “Male” radio button disabled when the form initially loads, then you need to modify the Male radio button as shown below.

<input type=”radio” name=”gender” value=”male” ngModel disabled>

Note: The most important point that you need to remember is, by default, the disabled form controls are not included in the Angular auto generated form model. 

In our example, the “Male” radio button is disabled, so, the gender property will not be included in the Angular generated form model. At this point, even if you select the Female radio button and submit the form, then also you will not see the gender property as shown in the below image.

How to disable a radio button in Angular Template Driven Forms?

In our example, we do not want any radio button to be disabled, so please remove the disabled attribute from the radio button.

In the next article, I am going to discuss the checkbox in angular template driven form with example. Here, in this article, I try to explain the radio buttons in angular Template Driven Forms. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.