Angular Radio Button Change Event
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.
Contents
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
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
citySelection(city: string) { console.log("Selected city: ", city); }
ts code:
selectedGrah = "";
<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
UsengModel
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
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 withngModel
.
<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
emp = {} as Employee; genderSelection() { console.log(this.emp.gender); }
5. Using FormControl
We can fetch checked radio button value usingformControl
.
<input type="radio" value="java" [formControl]="tech" (change)="techSelection()"> Java <input type="radio" value="angular" [formControl]="tech" (change)="techSelection()"> Angular
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; }
<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>
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); } }
<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>
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); } }
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); } }