Angular 16 Radio Buttons Tutorial with Examples

Last Updated on by in Angular
Angular Radio Buttons tutorial with examples is going to be discussed in this tutorial.We will learn to set and get values from Radio buttons using Reactive forms & Template-driven form.

Radio buttons are a well-known graphical user interface (GUI) element. Particularly, used in software application development, websites, and forms to allow users to select a single option from a given set of options.

Hence, these UI elements are called “radio buttons” because they are alike the buttons on a car radio that can only be tuned to one station at a time.

Radio buttons ideally seems like a small circular or rounded square buttons bestowed by text labels.

Only single option can be chosen at a time, and selecting a new option automatically unselect the previously chosen radio button.

Radio buttons are often used when there is a limited set of mutually exclusive options, and the user needs to choose one option from the given options.

Setup Angular App

Run the given below command to set up a basic Angular project.

ng new angular-radio-buttons-demo-reactive

# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? SCSS

Get into the project directory.

cd angular-radio-buttons-demo-reactive

No Property Access From Index Signature

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

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

Import ReactiveFormsModule and FormsModule in App Module

For making the radio buttons work with Reactive forms and Template-driven form we must import the given below forms services in app.module.ts file.

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

@NgModule({
  declarations: [...],
  imports: [
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [...],
  bootstrap: [...]
})

export class AppModule { }

Radio Buttons Example with Reactive Forms

In this part of the tutorial, I will share with you how you can manage radio buttons in Angular with Reactive forms.

  • Implement Radio Buttons
  • Set the initial value or selected value with Reactive forms
  • Validate radio buttons with Angular

Go to app.component.html file and add the following code.

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
   <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>

   <button type="submit">Submit</button>
</form>

Go to app.component.ts file and add the given below code:

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

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

export class AppComponent {
  isSubmitted = false;

  constructor(public fb: FormBuilder) {}

  registrationForm = this.fb.group({
    gender: [''],
  });

  get myForm() {
    return this.registrationForm.get('gender');
  }

  onSubmit() {
    this.isSubmitted = true;
    if (!this.registrationForm.valid) {
      return false;
    } else {
      return alert(JSON.stringify(this.registrationForm.value));
    }
  }
}

Radio Buttons Selected State with Angular Reactive Forms

To set selected state of radio buttons in Angular we need to pass the radio button’s value to the formcontrol array like given below.

registrationForm = this.fb.group({
  gender: ['male', [Validators.required]]
})

Validate Radio Buttons with Reactive Forms

To validate radio buttons in Angular we need to import the Validators service from @angular/forms. Then inject the Validators service in radio button’s form control array and access the validation method like given below.

import { FormBuilder, Validators } from "@angular/forms";

registrationForm = this.fb.group({
  gender: ['male', [Validators.required]]
})

Go to app.component.html and show the error in app’s front-end.

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
   <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 *ngIf="isSubmitted && myForm.invalid">
       Please select either value
   </div>

   <button type="submit">Submit</button>
</form>

Angular Radio Buttons Example with Template Driven Form

Since we all know forms are the backbone of any web and mobile app.

Forms are used to sign-in, place an order, flight booking, arrange a meeting, and many more data entry work.

In this part of the tutorial we are gong to work with Radio Buttons with Template Driven Form.

Go to the app.component.html template and add the below code to create the template driven form structure.

<form #myForm="ngForm" (submit)="templateForm(myForm.value)" novalidate>
  <div>
     <input id="male" type="radio" value="male" name="gender" ngModel>
     <label class="custom-control-label" for="male">Male</label>
  </div>

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

  <button type="submit">Find out gender</button>
</form>

The go to your app.component.ts file and add the following code.

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

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

export class AppComponent {
  constructor(public fb: FormBuilder) {}
  templateForm(value: any) {
    alert(JSON.stringify(value));
  }
}

Radio Buttons Validation with Angular Template-driven Form

To validate radio buttons with Angular template-driven form we need to follow the given below process.

app.component.html

<form #myForm="ngForm" (submit)="templateForm(myForm.value)" novalidate>
  <div>
     <input id="male" type="radio" value="male" name="gender" ngModel>
     <label class="custom-control-label" for="male">Male</label>
  </div>

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

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

  <button type="submit">Find out gender</button>
</form>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  isSubmitted = false;

  templateForm(value: any) {
    alert(JSON.stringify(value));
  }

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

Run the following command to serve your app locally:

ng serve --open

Open a web browser and navigate to:

 http://localhost:4200/

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.