View video tutorial
ANGULAR Radio Button
ANGULAR
Radio button functionality can be validated in an angular template-driven form when submitting a form.
Angular Radio button Example
➔ This example shows how radio button works in template driven form submission.
Create a project by ng new radio3 command.
ng new radio3
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 { Radio3Component } from './radio3/radio3.component';
@NgModule({
declarations: [
AppComponent,
TestComponent,
Radio3Component
],
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';
import { FormControl, FormGroup, NgForm, Validators } from '@angular/forms';
@Component({
selector: 'app-radio3',
templateUrl: './radio3.component.html',
styleUrls: ['./radio3.component.css']
})
export class Radio3Component implements OnInit {
constructor() { }
ngOnInit(): void {
}
radioGenders: any = {};
doSubmit(data: NgForm) {
this.radioGenders = data;
if (this.radioGenders.gender != "") {
console.log(this.radioGenders.gender);
} else {
console.log("You must select gender");
}
}
updateGen(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
<form #basicform="ngForm" (ngSubmit)="doSubmit(basicform.value)">
<div class="form-group">
<label for="gender">Gender:</label>
<div>
<input id="male" type="radio" value="male" name="gender" ngModel (change)="updateGen($event)">
<label for="male">Male</label>
</div>
<div>
<input id="female" type="radio" value="female" name="gender" ngModel (change)="updateGen($event)">
<label for="female">Female</label>
</div>
</div>
<button class="btn btn-success" type="submit" >Submit</button>
</form>
<div *ngIf='radioGenders.gender!=""; else err'>
You Selected : {{radioGenders.gender}}
</div>
<ng-template #err>You must select Gender</ng-template>
Copy the code and try it out practically in your learning environment.