In this tutorial, I am going to answer how to work with Angular Radio Buttons. As we know, there are 2 form types in Angular, template-drive form and reactive form.I’ll teach how to integrate radio buttons in a template-driven form and reactive form in an Angular app.
We’ll start with Template-driven form it is based on NgModel
and NgForm
directive. Whereas reactive form takes help of FormBuilder and FormControl classes to manage form elements.
Table of Contents
- Working with Radio Buttons in Template-driven Form in Angular
- Template-driven Radio Buttons Validation
- Radio Buttons with Angular Reactive Forms
- Reactive Forms Radio Button Validation
- Set Radio Button Selected in Angular
Working with Radio Buttons in Template-driven Form in Angular
Before working with radio buttons in template-driven form, we need to activate FormsModule
service in angular app. This service allows you to work with template-driven form in Angular. Go to app.module.ts
file and paste the following code.
import {FormsModule} from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule
]
})
Implementing Radio Buttons in Angular Template Driven Form
We are going to create radio buttons in Angular template. We’ll use ngModel
directive, this directive communicates with NgForm
directive.
<!-- Form starts -->
<form #myForm="ngForm" (submit)="templateForm(myForm.value)" novalidate>
<div class="custom-control custom-radio">
<input id="male" type="radio" class="custom-control-input" value="male" name="gender" ngModel>
<label class="custom-control-label" for="male">Male</label>
</div>
<div class="custom-control custom-radio">
<input id="female" type="radio" class="custom-control-input" value="female" name="gender" ngModel>
<label class="custom-control-label" for="female">Female</label>
</div>
<button type="submit" class="btn btn-danger btn-lg btn-block">Find out gender</button>
</form><!-- Form ends -->
Top comments (0)