Angular Material Radio Button Tutorial with Example

To implement a material radio button in Angular, you can use the “<mat-radio-button>” component. The <mat-radio-button> component provides the same functionality as a native <input type=”radio”> enhanced with Material Design styling and animations.

Radio-button label

The radio-button label is provided as the content of the <mat-radio-button> element.

The label can be positioned before or after a radio button by setting a labelPosition property to ‘before’ or ‘after‘.

If you don’t need the label to appear next to the radio button, you can use the aria-label or aria-labeled to specify an appropriate label.

Radio groups

Radio buttons should typically be placed inside the <mat-radio-group> unless the DOM structure would make that impossible (e.g., radio buttons inside table-cells).

The radio group has the value property that reflects the currently selected radio button inside the group.

Individual radio buttons inside the radio group will inherit the group’s name.

The <mat-radio-group> is compatible with @angular/forms and supports FormsModule and ReactiveFormsModule.

Here is the step-by-step guide to implement a fully functional radio button in Angular:

Step 1: Create an Angular project

I assume that you have the latest Angular CLI.

Type the following command to create an angular project.

ng new ang

We will install and configure Angular Material libraries.

Next, install hummer.js using the following command.

npm install --save hammerjs

Install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Include hammerjs inside the angular.json file.

You can find this file at the root of a project.

"scripts": [
     "./node_modules/hammerjs/hammer.min.js"
]

Step 2: Create a custom module file in Angular

Create a custom material.module.ts file and add the following code.

// material.module.ts

import { NgModule } from '@angular/core';

import { MatRadioModule, MatFormFieldModule, MatInputModule } from '@angular/material';

@NgModule({
  imports: [
    MatRadioModule,
    MatFormFieldModule,
    MatInputModule
  ],
  exports: [
    MatRadioModule,
    MatFormFieldModule,
    MatInputModule
  ]
})

export class MaterialModule { }

In the above code, we have included three modules.

  1. MatRadioModule: It is used to work with a material radio button.
  2. MatFormFieldModule: It is used to work with material form fields.
  3. MatInputModule: It is used to work validate the form values.

Step 3: Import a pre-built theme and Material icons

Angular Material comes with some pre-built themes.

You can add the following code to your global styles.css file to import the theme. The file is inside the src folder.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

You can also access the Material Design icons and use named icons with the <mat-icon> component.

Add the following link tag to the head section of your project’s root index.html file to import them to your project.

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Step 4: Import the material module and other modules

We will import the following modules inside the app.module.ts file.

  1. MaterialModule
  2. FormsModule
  3. ReactiveFormsModule
  4. BrowserAnimationsModule
// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MaterialModule } from './material.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    MaterialModule,
    ReactiveFormsModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 5: Build an angular radio button view and set the value

Write the following code inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  favoriteCartoon: string;
  cartoons: string[] = ['Tom and Jerry', 'Rick and Morty', 'Ben 10', 'Batman: The Animated Series'];
}

In the above code, we have defined two properties.

  1. favouriteCartoon(String)
  2. cartoons(Array of Strings)

We will loop through these cartoons in the view file and form the radio button group.

Add the following code inside the app.component.html file.

<!-- app.component.html -->

<label id="example-radio-group-label">Pick your favorite cartoon</label>
<mat-radio-group
  aria-labelledby="example-radio-group-label"
  class="radio-group"
  [(ngModel)]="favoriteCartoon">
  <mat-radio-button class="radio-button" *ngFor="let cartoon of cartoons" [value]="cartoon">
    {{ cartoon }}
  </mat-radio-button>
</mat-radio-group>
<div>Your favorite cartoon is: <b>{{ favoriteCartoon }}</b></div>

We use an angular ngfor directive to render all the radio button values.

The <mat-radio-group> supports two-way binding to the value property.

So, when the user selects any radio button, we get the value as favouriteCartoon, and we can either send the value to the server via AJAX request or do whatever we want.

Also, write the CSS code inside the app.component.css file.

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

.radio-button {
  margin: 5px;
}

Save the file and start the angular dev server using the following command.

ng serve -o

Angular Radio Button Example

From the output, you can see that we have selected Tom and Jerry, and in the footer, we can see that output printed. Thus, getting a value chosen in the radio button in Angular is effortless.

Angular radio button validation

When the user has not selected any radio button value, we will display the error, and when the user does select it, we need to remove that error.

We have already imported ReactiveFormsModule for this purpose inside the app.module.ts file.

Write the following code inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  favoriteCartoon: string;
  cartoons: string[] = ['Tom and Jerry', 'Rick and Morty', 'Ben 10', 'Batman: The Animated Series'];
  cartoonControl = new FormControl('', [Validators.required]);
}

We have imported the FormControl and Validators modules to validate the radio button. For that, we are creating the instance of FormControl called cartoonContol and setting the rules required.

We will attach that to the radio button form field and check the condition. If the cartoonControl has an error, then we will display it; otherwise, it will not.

The final step would be to write the app.component.html file.

<!-- app.component.html -->

<label id="example-radio-group-label">Pick your favorite cartoon</label>
<mat-radio-group
  aria-labelledby="example-radio-group-label"
  class="radio-group"
  [(ngModel)]="favoriteCartoon"
  [formControl]="cartoonControl">
  <mat-radio-button class="radio-button" 
    *ngFor="let cartoon of cartoons" 
    [value]="cartoon" >
    {{ cartoon }}
  </mat-radio-button>
</mat-radio-group>
<mat-error *ngIf="cartoonControl.hasError('required')">Please choose a cartoon</mat-error>
<div>Your favorite cartoon is: <b>{{ favoriteCartoon }}</b></div>

You can see that I have attached formControl inside the radio button, and now it tracks for the value, and if it finds empty, it returns an error; otherwise, it does not. Save the file and see the output.

Material Radio Button Validation

The error will be removed after you select from any of the buttons.

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.