Angular Radio Button Change Event

Written by: Arvind Rai,
Last updated:
December 24, 2023
On this page, we will learn to use change event in Angular radio button. The change event is fired for <input>, <select>, and <textarea> HTML elements when we modify its value.
In radio button, change event is fired when radio button is checked, but not when unchecked.
In Angular, change event is used as event binding i.e. (change)="onValueChange()" and in component we need to define this method. When we check the radio button, this method will be called.
Here we will learn in detail to access the checked value of radio button on its change event.

1. Using $event

To access checked value of radio button, pass $event to event binding method and access value as $event.target.value .
<input type="radio" value="red" name="myColor" (change)="colSelection($event)"> Red
<input type="radio" value="blue" name="myColor" (change)="colSelection($event)"> Blue 
Find the code in ts file.
colSelection(colEvent: any) {
	if (colEvent.target.value === 'red') {
		console.log("Color: Red");
	}
	else if (colEvent.target.value === 'blue') {
		console.log("Color: blue");
	}
} 

2. Passing Value

In event binding method, we can pass radio button values directly and when we check the radio button corresponding value is passed.
1.
<input type="radio" name="city" (change)="citySelection('Varanasi')"> Varanasi
<input type="radio" name="city" (change)="citySelection('PrayagRaj')"> PrayagRaj
<input type="radio" name="city" (change)="citySelection('Ayodhya')"> Ayodhya 
ts code:
citySelection(city: string) {
	console.log("Selected city: ", city);
} 
2. The same can also be achieved as following.
ts code:
selectedGrah = ""; 
HTML code:
<input type="radio" name="grah" (change)="selectedGrah = 'Prithvi'"> Prithvi
<input type="radio" name="grah" (change)="selectedGrah = 'Mangal'"> Mangal
<input type="radio" name="grah" (change)="selectedGrah = 'Shukra'"> Shukra

Selected Grah: {{selectedGrah}} 

3. Using ngModel

Use ngModel Directive with <input> element then pass template reference variable to event binding method by which we can access value of checked radio button.
<input type="radio" value="male" name="gender"
   ngModel (change)="genderSelection(empGen)"
   #empGen="ngModel"> Male
<input type="radio" value="female" name="gender" ngModel 
   (change)="genderSelection(empGen)" #empGen="ngModel"> Female 
ts code:
genderSelection(empGen: NgModel) {
	if (empGen.value === 'female') {
		console.log("Gender: female");
	}
	else if (empGen.value === 'male') {
		console.log("Gender: male");
	}
} 

4. Using Two-way Binding

We can fetch checked radio button value using two-way binding with ngModel.
<input type="radio" value="male" name="gender" 
  [(ngModel)]="emp.gender" (change)="genderSelection()"> Male
<input type="radio" value="female" name="gender" 
  [(ngModel)]="emp.gender" (change)="genderSelection()"> Female 
ts code:
emp = {} as Employee;
genderSelection() {
	console.log(this.emp.gender);
} 

5. Using FormControl

We can fetch checked radio button value using formControl .
<input type="radio" value="java"
    [formControl]="tech" (change)="techSelection()"> Java
<input type="radio" value="angular" 
    [formControl]="tech" (change)="techSelection()"> Angular 
ts code:
tech = new FormControl();
techSelection() {
	console.log(this.tech.value);
} 

6. Complete Example

Here I will create a complete demo application for radio button checked event. I will create a reactive form as well as a template-driven form.
In template-driven form, I will access checked radio button value using ngModel Directive.
In reactive form, I will create a FormGroup. Radio button <input> element will use formControlName to bind the value.

Now find the code.
employee.ts
export interface Employee {
	empName: string;
	gender: string;
	married: string;
} 
employee-reactive.component.html
<h3>Employee Reactive Form</h3>
<p *ngIf="isEmpDataValid && empForm.pristine" ngClass="success">
	Form submitted successfully.
</p>
<form [formGroup]="empForm" (ngSubmit)="onFormSubmit()">
	<table>
		<tr>
			<td>Name:</td>
			<td>
				<input formControlName="name">
				<div *ngIf="empForm.get('name')?.invalid && isEmpDataValid != null && !isEmpDataValid" ngClass="error">
					Name required.
				</div>
			</td>
		</tr>
		<tr>
			<td>Gender:</td>
			<td>
				<input type="radio" value="male" formControlName="gender" (change)="genderSelection()"> Male
				<input type="radio" value="female" formControlName="gender" (change)="genderSelection()"> Female
				<div *ngIf="empForm.get('gender')?.invalid && isEmpDataValid != null && !isEmpDataValid"
					ngClass="error">
					Gender not selected.
				</div>
			</td>
		</tr>
		<tr>
			<td>Married? </td>
			<td>
				<input type="radio" value="yes" formControlName="married" (change)="marriedSelection()"> Yes
				<input type="radio" value="no" formControlName="married" (change)="marriedSelection()"> No
				<div *ngIf="empForm.get('married')?.invalid && isEmpDataValid != null && !isEmpDataValid"
					ngClass="error">
					Are you married?
				</div>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<button>Submit</button>
				<button type="button" (click)="reset()">Reset</button>
			</td>
		</tr>
	</table>
</form> 
employee-reactive.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';

import { EmpService } from './services/emp-service';
import { Employee } from './domain/employee';
import { CommonModule } from '@angular/common';

@Component({
	selector: 'app-reactive',
	standalone: true,
	imports: [ReactiveFormsModule, CommonModule],
	templateUrl: './employee-reactive.component.html',
	styleUrls: ['./style.css']
})
export class EmpReactiveComponent {
	isEmpDataValid!: boolean;
	empForm = new FormGroup({
		name: new FormControl('', Validators.required),
		gender: new FormControl('', Validators.required),
		married: new FormControl('', Validators.required)
	});
	user!: Employee;
	constructor(private userService: EmpService) {
	}
	onFormSubmit() {
		this.isEmpDataValid = false;
		if (this.empForm.invalid) {
			return;
		}
		this.isEmpDataValid = true;
		this.user = {
			empName: this.empForm.get('name')?.value ?? "",
			gender: this.empForm.get('gender')?.value ?? "",
			married: this.empForm.get('married')?.value ?? ""
		}
		this.userService.createEmployee(this.user);
		this.reset();
	}
	reset() {
		this.empForm.reset({
			married: ""
		});
	}
	get gender() {
		return this.empForm.get('gender')?.value;
	}
	get married() {
		return this.empForm.get('married')?.value;
	}
	genderSelection() {
		console.log("Selected gender: ", this.gender);
	}
	marriedSelection() {
		console.log("Married: ", this.married);
	}
} 
emp-template-driven.component.html
<h3>Employee Template-Driven Form</h3>
<p *ngIf="isEmpDataValid" ngClass="success">
	Form submitted successfully.
</p>
<form #empForm="ngForm" (ngSubmit)="onFormSubmit(empForm)">
	<table>
		<tr>
			<td>Name:</td>
			<td>
				<input name="empName" [ngModel]="emp.empName" required #ename="ngModel">
				<div *ngIf="ename.invalid && empForm.submitted && !isEmpDataValid" ngClass="error">
					Name required.
				</div>
			</td>
		</tr>
		<tr>
			<td>Gender:</td>
			<td>
				<input type="radio" value="male" name="gender" [(ngModel)]="emp.gender" (change)="genderSelection()"
					required #gender="ngModel"> Male
				<input type="radio" value="female" name="gender" [(ngModel)]="emp.gender" (change)="genderSelection()"
					required #gender="ngModel"> Female
				<div *ngIf="gender.invalid && empForm.submitted && !isEmpDataValid" ngClass="error">
					Gender not selected.
				</div>
			</td>
		</tr>
		<tr>
			<td>Married? </td>
			<td>
				<input type="radio" value="yes" name="married" [(ngModel)]="emp.married" (change)="marriedSelection()"
					required #married="ngModel"> Yes
				<input type="radio" value="no" name="married" [(ngModel)]="emp.married" (change)="marriedSelection()"
					required #married="ngModel"> No
				<div *ngIf="married.invalid && empForm.submitted && !isEmpDataValid" ngClass="error">
					Are you married?
				</div>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<button>Submit</button>
				<button type="button" (click)="resetForm(empForm)">Reset</button>
			</td>
		</tr>
	</table>
</form> 
emp-template-driven.component.ts
import { Component, OnInit } from '@angular/core';
import { FormsModule, NgForm, NgModel } from '@angular/forms';

import { EmpService } from './services/emp-service';
import { Employee } from './domain/employee';
import { CommonModule } from '@angular/common';

@Component({
	selector: 'app-template',
	standalone: true,
	imports: [FormsModule, CommonModule],
	templateUrl: './emp-template-driven.component.html',
	styleUrls: ['./style.css']
})
export class EmpTemplateDrivenComponent {
	isEmpDataValid = false;
	emp = {} as Employee;
	constructor(private userService: EmpService) {
	}
	onFormSubmit(form: NgForm) {
		this.isEmpDataValid = false;
		if (form.invalid) {
			return;
		}
		this.isEmpDataValid = true;
		this.emp.empName = form.controls['empName'].value;
		this.emp.gender = form.controls['gender'].value;
		this.emp.married = form.controls['married'].value;
		this.userService.createEmployee(this.emp);
		this.resetForm(form);
	}
	resetForm(form: NgForm) {
		this.emp = {} as Employee;
		form.resetForm({
			gender: "",
			married: ""
		});
	}
	genderSelection() {
		console.log("Selected gender: ", this.emp.gender);
	}
	marriedSelection() {
		console.log("Married: ", this.emp.married);
	}
} 
emp-service.ts
import { Injectable } from '@angular/core';
import { Employee } from '../domain/employee';

@Injectable({
   providedIn: 'root'
})
export class EmpService {
   createEmployee(emp: Employee) {
      console.log("Emp Name: " + emp.empName);
	   console.log("Gender: " + emp.gender);
	   console.log("Married?: " + emp.married);
   }   
} 
Find the print-screen of the output.
Angular Radio Button Change Event

7. References

8. Download Source Code

Join the Newsletter

(Subscribe to get our latest content directly into your inbox)

WRITTEN BY
ARVIND RAI
ARVIND RAI









©2024 concretepage.com | Privacy Policy | Contact Us