Angular 11 Radio Buttons Reactive and Template-driven Examples

Throughout this extensive angular 11 radio buttons example tutorial, you will find out how to work with radio buttons in Angular using reactive forms and template-driven forms.

Form input in a reactive way communicates using form control wrapped around the form group and compose a form object. Reactive forms are specially built on observable stream to empower reactive programming.

The first section of this post covers the angular radio button reactive form example. We will ascertain how to create radio button, get radio button value, set selected value in radio button, and validate radio button in Angular using reactive form technique.

The second section of this tutorial will show you the angular radio button template-driven approach using ng model directive. FYI, we will use the Bootstrap CSS framework to design Radio button elements in Angular.

Nevertheless, why Template-driven radio buttons approach is useful. Thats because creating a programming logic is simple in the template-driven environment; you define controls, validation inside the angular HTML template, luckily it also supports the two-way data binding and works as a mnemonic for a template when it comes to updating the changes in the model.

Install Angular App

Start installing the new angular app, nonetheless you can skip if already installed:

ng new angular-radio-button-example

Move to project root:

cd angular-radio-button-example

Add Forms Module and Reactive Forms Module

This step comprises of importing and adding FormsModule and ReactiveFormsModule in imports array in app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

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

export class AppModule { }

Angular Template-Driven Radio Buttons Example

Now, you will create a radio button with ngModel the template-driven approach, import NgForm from ‘@angular/forms’ package, and bind with the change event:

Update 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.scss']
})

export class AppComponent {
  
  submitted = false;

  constructor() { }

  onChange(form: NgForm) {
    this.submitted = true;

    if(!form.valid) {
      return false;
    } else {
      console.log(form.value.gender)
    }
  }

}

Set the change event, connect with the ngForm directive to make the two-way data binding, and declare ngModel with a radio button element.

Update app.component.html file:

<div class="container mt-5">

  <h2>Angular Radio Button Template Driven Demo</h2>

  <form #tdForm="ngForm" (change)="onChange(tdForm)" novalidate>
    <div class="form-check">
      <input class="form-check-input" type="radio" value="male" name="gender" id="male" ngModel required>
      <label class="form-check-label" for="male">
        Male
      </label>
    </div>

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

    <button type="submit" class="btn btn-primary mt-4">Check</button>
  </form>

</div>

Angular Reactive Forms Radio Buttons Example

This step brings us to understand creating a radio button with a reactive forms approach, you have to import FormBuilder API to create a form object. Also, to add validation in the radio button, you have to import the Validators API from “@angular/forms”:

Update app.component.ts file:

import { Component } from '@angular/core';
import { FormGroup, Validators, FormControl } from '@angular/forms';


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

export class AppComponent {

  submitted = false;
   
  reactiveForm = new FormGroup({
    gender: new FormControl('', Validators.required)
  });
   
  get checkValidaiton(){
    return this.reactiveForm.controls;
  }
   
  onSubmit(){
    this.submitted = true;
    console.log(this.reactiveForm);
  }
 
  updateGender(event) {
    console.log(event.target.value);
  }

}

Update app.component.html file:

<div class="container mt-5">

  <h2>Angular Radio Button with Reactive Forms Demo</h2>

  <form [formGroup]="reactiveForm" (ngSubmit)="onSubmit()">

   <!-- Validaiton Message -->
   <div class="alert alert-danger" *ngIf="submitted && checkValidaiton.gender.invalid">
      <p>Value must be selected</p>
   </div>

    <div class="form-check">
      <input type="radio" class="form-check-input" value="male" name="gender" formControlName="gender" (change)="updateGender($event)">
      <label class="form-check-label">
        Male
      </label>
    </div>

    <div class="form-check">
      <input type="radio" class="form-check-input" value="female" name="gender" formControlName="gender" (change)="updateGender($event)">
      <label class="form-check-label">
        Female
      </label>
    </div>

    <button type="submit" class="btn btn-primary mt-4">Check</button>
  </form>

</div>

Run the application with below command:

ng serve --open

The tutorial is over, have a good day!

Angular Radio Buttons Reactive and Template-driven Examples