How to implement the Angular Radio button?

Angular radio button input allows the user to select only one option from a list of choices. Angular doesn’t have a radio button component, we can use a native HTML radio button or Angular material radio button. Angular material UI library has a radio input component called mat-radio-group and mat-radio-button.

In this tutorial, we‘ll learn how to add and use the radio button in the Angular form. We’ll demonstrate an example Angular material radio button example on both template-driven and reactive form. Let get started.

What is the radio input element in Angular?

The native HTML radio is an input element with a type attribute radio. Here is the syntax of HTML radio input.

<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label>

The HTML Radio buttons are elements of type radio that are generally used in radio groups: collections of radio buttons describing a set of related options. We can group the radio button using a common name among all related radio buttons.

Here we have used name=”fav_language” for two radio buttons and we can select either one of them only. The HTML radio buttons are typically rendered as small circles, which are filled or highlighted when selected.

<mat-radio-button> provides the same functionality as a native <input type="radio"> enhanced with Material Design styling and animations.


Setting up and configuring Angular material radio button

Let’s first demonstrate the Angular radio button input using the material design radio component, here we had listed the abstract step of adding the Angular mat-radio-group

  1. Create Angular material radio button project.
  2. Add Angular material library to our Angular project.
  3. Import MatRadioModule, FormsModule, and ReactiveFormsModule to our project.
  4. Defining form group and form control for the radio button.
  5. Add mat-radio-group and mat-radio-button components in the component template.
angular radio button example
Angular mat-radio-group example one

Step 1 to 3: Setup and configure angular material radio button project

Let’s first create an Angular material radio button project, we need to install the angular material library. We have a complete tutorial on the best approach to adding material in Angular.

ng new radioApp
cd new radioApp
ng add @angular/material

The material radio allows us to select only one option among lists of options and it provides this functionality with Material Design look and feels and behavior. To use the Angular material radio we need to import MatRadioModule in our app module. Let’s import it into our app.component.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatRadioModule } from '@angular/material/radio';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatRadioModule,
    MatIconModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have also imported a few material modules in our Angular project, to demonstrate the Angular material radio button with a reactive form with other fields.

Step 4 to 5 Angular radio button in Template-driven form

To understand how to use the Angular material radio, let’s demonstrate an example of it in Angular template form. Here is a screenshot of our example.

angular radio button
Angular mat-radio-group

Let first define any string array containing a list of countries’ names in our component typescript file.

countries: Array<any> = [
    { name: 'India', value: 'india' },
    { name: 'France', value: 'france' },
    { name: 'USA', value: 'USA' },
    { name: 'Germany', value: 'germany' },
    { name: 'Japan', value: 'Japan' }
];

In our component template, we can define the Angular material radio button using the mat-radio-group and its subcomponent mat-radio-button.

<section>
 <form #f="ngForm" (ngSubmit)="submit()">
   <label id="example-radio-group-label">
    Pick your favorite country: Angular radio button ngmodel
   </label>
   <mat-radio-group aria-labelledby="example-radio-group-label" 
    class="example-radio-group" [(ngModel)]="selectedCountry" name="selectedCountry">
     <mat-radio-button class="example-radio-button" 
       *ngFor="let country of countries" [value]="country.name">
         {{ country.name }}
     </mat-radio-button>
     </mat-radio-group>
  </form>
 <div>Selected Country: {{ f.value |json }}</div>
</section>

Angular material radio button components

NameDescription
mat-radio-groupIs the root component for all related mat-radio-button subcomponents. The radio group has a value property that reflects the currently selected the radio-button inside of the group. We have used ngModel as a value property to get selected radio button
mat-radio-buttonThe mat-radio-button provides the same functionality as a native <input type="radio"> enhanced with Material Design styling and animations

Angular radio button input in Reative form

In our second example, we’ll demonstrate the Angular material radio button in the reactive form and we’ll also add reactive form validation to it. The submit button is disabled when a reactive form is invalid. Here is a screenshot of your Angular material radio button with reactive form.

Angular radio button example
mat-radio-group required validation

Angular radio button validation

Let first define reactive form and its form control elements in the app.component.ts file. We will also add radio button validation.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  form: FormGroup;

  countries: Array<any> = [
    { name: 'India', value: 'india' },
    { name: 'France', value: 'france' },
    { name: 'USA', value: 'USA' },
    { name: 'Germany', value: 'germany' },
    { name: 'Japan', value: 'Japan' }
  ];

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      name: [null, [Validators.required, Validators.minLength(10)]],
      email: [null, [Validators.required, Validators.pattern("^[a-z0-9._%+-][email protected][a-z0-9.-]+\\.[a-z]{2,4}$")]],
      country: [null, [Validators.required]],
    });
  }

  changeCountry(event: any) {
    console.log(event.value);
  }

  submit() {
    console.log(this.form.value);
  }
}

We defined country name as one of the form control fields of reactive form. Now let’s add our Angular material radio button component and other fields in our component template.

<section>
 <form [formGroup]="form" (ngSubmit)="submit()">
   <div class="form-group">
     <mat-form-field appearance="standard">
       <mat-label>Name</mat-label>
       <input matInput maxlength="15" inputmode="tel" placeholder="Type name" formControlName="name" #nameInput>
       <mat-hint>Mini character 10: {{ nameInput.value.length }}/10</mat-hint>
       <mat-error>Name is required</mat-error>
       <mat-error *ngIf="form.controls['name'].errors?.minlength">
         Please enter more than 10 character
       </mat-error>
     </mat-form-field>
    </div>

    <div class="form-group">
     <mat-form-field appearance="legacy">
       <mat-label>Email Address:</mat-label>
       <input matInput type="email" formControlName="email" placeholder="Your email">
        <mat-icon matSuffix>mail_outline</mat-icon>
        <mat-hint>Input the fully qualified email address</mat-hint>
        <mat-error *ngIf="form.controls['email'].errors?.required">Email is required</mat-error>
        <mat-error *ngIf="form.controls['email'].errors?.pattern">Please enter valid email</mat-error>
        </mat-form-field>
     </div>

    <div class="example-section">
      <mat-radio-group formControlName="country" aria-labelledby="example-radio-group-label" class="example-radio-group">
       <mat-radio-button class="example-radio-button" *ngFor="let country of countries" [value]="country.name" (change)="changeCountry($event)">
            {{ country.name }}
       </mat-radio-button>
      </mat-radio-group>
   </div>
   <button mat-raised-button color="accent" [disabled]="form.invalid">Submit</button>
  </form>
  <p>{{ form.value | json }}</p>
</section>

We had added design on our material radio button, let’s add CSS style in component style files.

.example-radio-group {
  display: flex;
  flex-direction: column;
  margin: 15px 0;
}
      
.example-radio-button {
   margin: 5px;
 }

Angular radio button using native HTML radio button

We have learned that Angular doesn’t have a radio button component, we have used Angular material radio button component. Let’s demonstrate an example of a radio button using HTML input with attribute type radio.

Angular radio button example
<div>
  <h5>Gender</h5>
  <label>
    <input type="radio" value="male" name="gender">Male
  </label><br />
  <label>
    <input type="radio" value="female" name="gender">Female
  </label><br />
  <label>
    <input type="radio" value="other" name="gender">Other
  </label>
</div>

Angular radio button checked

We can set a default value of the Angular radio button checked using the checked attribute in radio input.

<input type="radio" value="male" name="gender" checked>Male

Angular radio button using bootstrap UI

We can use the bootstrap CSS class name on Angular radio button input. Here is a screenshot of our example.

Angular bootstrap radio button

To use bootstrap, we need to install the ng-bootstrap in our Angular project. Run the following command to add bootstrap to our Angular project.

ng add @ng-bootstrap/ng-bootstrap
   <div class="custom-control custom-radio">
    <input type="radio" class="custom-control-input" id="defaultUnchecked" name="defaultExampleRadios" mdbInput>
    <label class="custom-control-label" for="defaultUnchecked">Default unchecked</label>
  </div>

  <!-- Default checked -->
  <div class="custom-control custom-radio">
    <input type="radio" class="custom-control-input"  
      id="defaultChecked" name="defaultExampleRadios" checked mdbInput>
    <label class="custom-control-label" for="defaultChecked">Default checked</label>
  </div>

  <br />
  <div class="btn-group btn-group-toggle" 
    ngbRadioGroup name="radioBasic" [(ngModel)]="model">
    <label ngbButtonLabel class="btn-primary">
      <input ngbButton type="radio" value="left"> Left
    </label>
    <label ngbButtonLabel class="btn-primary">
      <input ngbButton type="radio" value="middle"> Middle
    </label>
    <label ngbButtonLabel class="btn-primary">
      <input ngbButton type="radio" value="right"> Right
    </label>
  </div>

Conclusion
We learned how to use Angular radio button input. We have plenty of choices to use checkbox input from Angular material radio button, native HTML radio input, bootstrap radio input also.

Related Articles

Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top