View video tutorial
ANGULAR Radio button
ANGULAR
Radio buttons can be implemented using the ngModel Angular directive in a template-driven form.
Angular Radio button Example
➔ This example shows how radio button works in template driven form.
Create a project by ng new radio1 command.
ng new radio1
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 { Radio1Component } from './radio1/radio1.component';
@NgModule({
declarations: [
AppComponent,
TestComponent,
Radio1Component
],
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-radio1',
templateUrl: './radio1.component.html',
styleUrls: ['./radio1.component.css']
})
export class Radio1Component implements OnInit {
constructor() { }
ngOnInit(): void {
}
selectedGender: string = "Male";
onRadioClick(e: string): void {
this.selectedGender = e;
}
isSelected(name: string): boolean {
if (!this.selectedGender) { // if no radio button is selected, always return false so every nothing is shown
return false;
}
return (this.selectedGender === name); // if current radio button is selected, return true, else return false
}
onchangeRadio(e: any) {
console.log(e.target.value);
}
}
Copy the code and try it out practically in your learning environment.
HTML file
Copy this file content to the target file.
Example
<div class="radio">
<label>
<input type="radio" name="gender" value="Male" (click)="onRadioClick('Male')" (change)="onchangeRadio($event)" [ngModel]="selectedGender">
Male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="Female" (click)="onRadioClick('Female')" (change)="onchangeRadio($event)" ngModel >
Female
</label>
</div>
<div *ngIf="isSelected('Male')">
<input type="text" [value]="selectedGender" />{{selectedGender}} radio button selected
</div>
<div *ngIf="isSelected('Female')">
<input type="text" [value]="selectedGender" /> {{selectedGender}} radio button selected
</div>
Copy the code and try it out practically in your learning environment.