Angular 16 Radio Buttons Tutorial with Example

Last Updated on by in Angular
In this tutorial, we will share how to work with Radio Buttons in Angular. Since Angular offers two types of forms, Template-Driven and Reactive Forms, we will choose both approaches to help you learn to implement radio buttons in angular, respectively.We’ll start with Template-Driven Form it is based on NgModel and NgForm directive. Whereas reactive form takes help of FormBuilder and FormControl classes to manage form elements.

Set up Angular Project

Install the Angular CLI with below command.

npm install @angular/cli -g

Now, you have to install the brand new Angular project using below command.

ng new angular-demo

Angular CLI asks for your choices while setting up the project…

Would you like to add Angular routing?
Select y and Hit Enter.

Which stylesheet format would you like to use? (Use arrow keys)
Choose SCSS and hit Enter

Use command to navigate into the project directory:

cd angular-demo

Remove Angular TypeScript Errors

To get rid from the strict TypeScript errors:

Make sure to set following properties to false in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
},
  "angularCompilerOptions": {
    "strictTemplates": false
  }

Working with Radio Buttons in Template-driven Form in Angular

Before working with radio buttons in template-driven form, we need to activate FormsModule service in angular app. This service allows you to work with template-driven form in Angular.

Go to app.module.ts file and paste the following code.

import {FormsModule} from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ]
})

Implementing Radio Buttons in Angular Template Driven Form

We are going to create radio buttons in Angular template. We’ll use ngModel directive, this directive communicates with NgForm directive.

<!-- Form starts -->
<form #myForm="ngForm" (submit)="templateForm(myForm.value)" novalidate>

   <div class="custom-control custom-radio">
      <input id="male" type="radio" class="custom-control-input" value="male" name="gender" ngModel>
      <label class="custom-control-label" for="male">Male</label>
   </div>

   <div class="custom-control custom-radio">
      <input id="female" type="radio" class="custom-control-input" value="female" name="gender" ngModel>
      <label class="custom-control-label" for="female">Female</label>
   </div>

   <button type="submit" class="btn btn-danger btn-lg btn-block">Find out gender</button>
</form><!-- Form ends -->

Getting Radio Buttons Value in Angular Component Class

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

@Component({
 // ...
})

export class AppComponent {
  
  constructor() {}

  /*########### Template Driven Form ###########*/
  templateForm(value: any) {
    alert(JSON.stringify(value));
  }

}

Template-driven Radio Buttons Validation in Angular

In order to implement Angular vlidation on radio buttons, use the following code.

app.component.html

<!-- Form starts -->
<form #myForm="ngForm" (submit)="submitForm(myForm)" novalidate>
   <!-- Gender -->
   <div>
      <input id="male" type="radio" class="custom-control-input" value="male" name="gender" ngModel required>
      <label class="custom-control-label" for="male">Male</label>
   </div>

   <div>
      <input id="female" type="radio" class="custom-control-input" value="female" name="gender" ngModel required>
      <label class="custom-control-label" for="female">Female</label>
   </div>

   <div *ngIf="isSubmitted && myForm.invalid">
      <p>Please select either value</p>
   </div>

   <!-- Submit Button -->
   <button type="submit" class="btn btn-danger btn-lg btn-block">Find out gender</button>
</form><!-- Form ends -->

app.component.ts

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 {
  isSubmitted = false;

  constructor() {
  }

  /*########### Template Driven Form ###########*/
  submitForm(form: NgForm) {
    this.isSubmitted = true;
    if(!form.valid) {
      return false;
    } else {
    alert(JSON.stringify(form.value))
    }
  }

}

Radio Buttons in Template-Driven Angular Form Demo

Angular Radio Buttons with Reactive Forms Example

Now I am going to build radio buttons using Angular reactive forms.

I will show you how to implement, set selected value and validate radio buttons in Angular app. I’ll use Reactive Form’s FormBuilder, FormControl, and ReactiveFormsModule service to handle radio buttons.

Go to app.module.ts file and paste the following code.

  • FormBuilder: It allows to build an AbstractControl from a user-specified configuration..
  • FormGroup: FormGroup service maintains the values, properties and validation state of a specific group of AbstractControl.
  • FormControl: This service manages the value and validation status of a specific form control.
  • ngSubmit: It’s an event which triggers when the form is submit button is clicked.
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ]
})

Integrating Radio Buttons in Reactive Forms

Now i will show you how to integrate Radio Buttons in Reactive forms. Let’s understand the Reactive Form’s services:

app.component.html

<!-- Form starts -->
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
   <!-- Gender -->
   <div>
      <input id="male" type="radio" class="custom-control-input" value="male" name="gender" formControlName="gender">
      <label class="custom-control-label" for="male">Male</label>
   </div>

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

   <div *ngIf="isSubmitted && myForm.invalid">
      <p>Please select either value</p>
   </div>

   <!-- Submit Button -->
   <button type="submit">Submit</button>
</form><!-- Form ends -->

app.component.ts

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


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

export class AppComponent {

  constructor(public fb: FormBuilder) {
  }

  /*########### Template Driven Form ###########*/
  registrationForm = this.fb.group({
    gender: ['male']
  })

  // Submit Registration Form
  onSubmit() {
      alert(JSON.stringify(this.registrationForm.value))
  }  

}

Radio Buttons Validation with Reactive Forms

In order to validate radio buttons using reactive forms, we need to take help of getter methods. Getter method allow us to access form control element.

// Getter method to access form control
get myForm() {
  return this.registrationForm.get('gender');
}

Access errors within Angular template using getters.

<!-- Form starts -->
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
  <div>
    <input
      id="male"
      type="radio"
      value="male"
      name="gender"
      formControlName="gender"
    />
    <label class="custom-control-label" for="male">Male</label>
  </div>

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

  <!-- Showing error method -->
  <div *ngIf="isSubmitted && myForm.errors?.['required']">
    <p>Please select either value</p>
  </div>

  <button type="submit">Submit</button>
</form>
<!-- Form ends -->

Set Radio Button Selected in Angular

To set the Radio Button selected in Angular, we will pass the radio button’s value in the from control array like given below. It will set selected value of radio button in Angular’s Reactive Forms.

 registrationForm = this.fb.group({
    gender: ['male'] // Pass the name value in form control array.
  })

Check Out the Radio Buttons with Reactive Form

The following command will invoke the development server, compile and run your app.

ng serve --open