DEV Community

DEEGAMBER SINGH
DEEGAMBER SINGH

Posted on • Originally published at positronx.io on

Angular 9|8|7 Radio Buttons Example

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

  1. Working with Radio Buttons in Template-driven Form in Angular
  2. Template-driven Radio Buttons Validation
  3. Radio Buttons with Angular Reactive Forms
  4. Reactive Forms Radio Button Validation
  5. 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 -->

Getting Radio Buttons Value in Angular Component Class

click here to read more

Top comments (0)