Angular 13 Radio Buttons Reactive Form Example Tutorial

In this tutorial, we will learn how to create radio buttons in Angular, implement radio buttons in a way that we can easily set the values and get the values from radio buttons.

A radio button or option button is a graphical control element that allows the user to choose only one of a predefined set of mutually exclusive options.

We will use Reactive Forms and Template-driven methods to handle Radio Buttons in Angular.

Reactive forms provide a model-driven method for managing form inputs whose values change over time. It allows you to create dynamic forms where you can add or remove controls at run time.

Template-driven forms use two-way data binding to update the component’s data model as changes are made in the template and vice versa.

Create Angular Project

If you haven’t installed the angular app, then you execute the command to create the app.

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

ng new angular-radio-buttons-example

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

Head over to the project root.

cd angular-radio-buttons-example

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Import and Register Reactive Forms Module

We have to import and register ReactiveFormsModule and FormsModule in app.module.ts file.

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

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

export class AppModule { }

Handle Radio Button with Reactive Forms

We will use the reactive forms approach to answer the following questions:

  1. How to create radio buttons in angular?
  2. How to set the initial value in angular radio buttons?
  3. How to validate radio buttons in angular?

Set Selected State of Radio Button

You can use the following code to set the selected state of a Radio Button with Reactive Forms approach in Angular.

contactForm = this.fb.group({
  gender: ['male']
})

Implement Validation in Radio Buttons

We can easily implement the validation in radio buttons, import the Validators service from “@angular/forms”

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

Inject the validation service in the form group array, and it will assimilate the validation in radio buttons.

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

Add following code in app.component.ts file.

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

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

export class AppComponent {
  isSet = false;

  constructor(public fb: FormBuilder) { }

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

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

  onSubmit() {
    this.isSet = true;
    if (!this.contactForm.valid) {
      return false;
    } else {
      console.log(JSON.stringify(this.contactForm.value))
    }
  }
}

Add following code in app.component.html file.

<form [formGroup]="contactForm" (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="isSet && myForm.invalid">
       Please select one option
   </div>

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

Handle Radio Buttons with Template-Driven Approach

Let’s create the Radio Buttons with Template Driven approach.

Place the following code in app.component.ts file.

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 {

  onSubmit(form: NgForm) {
    console.log(JSON.stringify(form));
   }

}

Include the following code in app.component.html file.

<form #myForm="ngForm" (submit)="onSubmit(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">Check</button>
</form>

Finally, the Angular Radio Buttons tutorial is over; please share your valuable feedback to improve this tutorial.