View video tutorial
ANGULAR Radio Button
ANGULAR
Radio button functionality can be implemented in an angular template-driven form using the ngModel angular directive.
Angular Radio button Example
➔ This example shows how radio button works with event in template driven form.
Create a project by ng new radio2 command.
ng new radio2
app.module.ts file
Copy this file content to the target file.
Example
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import {FormsModule} from '@angular/forms';
import { Radio2Component } from './radio2/radio2.component';
@NgModule({
declarations: [
AppComponent,
TestComponent,
Radio2Component,
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Copy the code and try it out practically in your learning environment.
Class file
Copy this file content to the target file.
Example
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-radio2',
templateUrl: './radio2.component.html',
styleUrls: ['./radio2.component.css']
})
export class Radio2Component implements OnInit {
constructor() { }
ngOnInit(): void {
}
radio_val: string = "";
selectedRadio: string = "";
onRadioChange(val: any) {
this.radio_val = val;
if (val == 0) {
this.selectedRadio = "Female"
} else if (val == 1) {
this.selectedRadio = "Male"
} else {
this.selectedRadio = "Trans"
}
}
onRadioClick(val: any) {
//this.radio_val = val;
}
}
Copy the code and try it out practically in your learning environment.
HTML file
Copy this file content to the target file.
Example
<input type="radio" name="test" value='0' #r0 [(ngModel)]='radio_val' (change)='onRadioChange(r0.value)' (click)='onRadioClick(0)'/>Female
<input type='radio' name='test' value='1' #r1 [(ngModel)]='radio_val' (change)='onRadioChange(r1.value)' (click)='onRadioClick(1)'/>Male
<input type='radio' name='test' value='2' #r2 [(ngModel)]='radio_val' (change)='onRadioChange(r2.value)' (click)='onRadioClick(2)'/>Trans
<br>
You selected: {{selectedRadio}}
Copy the code and try it out practically in your learning environment.