Angular 7 Radio Buttons Example

Article By Rawat Digamber on
In this tutorial, I am going to answer how to work with Angular 7 Radio Buttons. As we know, there are 2 form types in Angular, template-drive form and reactive form.I’ll teach how to integrate radio buttons in a template-driven form and reactive form in an Angular app.

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.

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 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

Radio Buttons with Angular Reactive Forms

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 -->

Below is the complete logic of radio buttons in Angular 7.

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

  constructor(public fb: FormBuilder) { }

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

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

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

}

Set Radio Button Selected in Angular 7

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

Feel free to contact me, If you are looking for a freelance web and mobile app developer in India, with the following skills: Angular JS, Angular 2+, Node JS, Firebase, MongoDB, Ionic Framework and WordPress.

I also offer remote contracting services to clients across the globe.

Get Started