AppDividend
Latest Code Tutorials

Angular Radio Button Example | Material Radio Button

0

In this Angular 9 radio button example, we will use the Angular Material library to construct UI/UX. Angular Materials offer a lot of built-in modules for your project. Features such as autocomplete, datepicker, slider, menus, grids, and toolbar are available for use with materials in Angular 9. Now let’s recall the radio button in html 5.

Radio Button in HTML 5

A radio button is simply the input element with a type property set to the radio.

<input type="radio">

As with all input elements of HTML, you need to define a name for it to be used because without a name, the element won’t be identifiable when posting the form back to a server for processing.

You also want to set value, and this will be the value sent to the server if the radio button has been selected.

See the following snippet.

<input type="radio" name="cartoon" value="Rick and Morty">

The name attribute is used to specify an entire group of radio objects.

The single radio button does not make sense, so you need a group of radio buttons because, for a single item, you can use the checkbox, and there is no need for a radio button.

Radio Button vs. Checkbox in HTML 5

In HTML Forms, radio buttons seem a lot like checkboxes, but they are different in several important ways.

  1. Radio buttons occur only in groups. You can have one checkbox on the form, but radio buttons make reason only when placed in the groups.

  2. Only one element can be selected. Selecting one radio button deselects the others.

  3. The id of each radio button is unique. Each id on the Web page must be unique, and the id elements of each radio button follow these rules.

  4. Each radio element also has the name attribute. The name attribute is used to specify an entire group of radio objects.

  5. All radio buttons in the group have the same name. HTML uses the name attribute to figure out which group the radio button is in and to ensure that only one button in the group is selected.

Angular Radio Button

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

In the radio button, the user can only select one value at a time; that is why radio-buttons with the same name comprise a set from which the only one may be selected at one time.

Radio-button label

The radio-button label is provided as the content to 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-labelledby to specify an appropriate label.

Radio groups

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

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

Individual radio-buttons inside of the radio-group will inherit the name of the group.

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

Angular 9 Radio Button Example

The angular Material library offers many components. We have covered the following components in this blog.

  1. Angular material table
  2. Angular material modal
  3. Angular material icon
  4. Angular material select

Let’s create an Angular 9 project and install Angular material libraries and configure it.

Step 1: Create Angular 9 project

I assume that you have the latest Angular CLI.

Type the following command to create an angular project.

ng new ang

Now, we will install and configure Angular Material libraries.

Next, install hummer.js using the following command.

npm install --save hammerjs

Now, install Angular Material and Angular Animations using the following command.

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

Now, include hammerjs inside the angular.json file.

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

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

Step 2: Create a custom module file in Angular 9

Now, 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.

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

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

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

To import them to your project, you can add the following link tag to the head section of your project’s root index.html file.

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

Step 4: Import 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 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 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 are using an angular ngfor directive to render all the values of the radio button.

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 to do.

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. It is effortless to get selected value in the radio button in Angular 9.

Angular radio button validation example

Okay, now, let’s validate the radio button element.

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

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

Now, 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 module because we need to validate the radio button. For that, we are creating the instance of FormControl called cartoonContol and set 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 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, then return an error otherwise not. Save the file and see the output.

Material Radio Button Validation

After you select from any of the buttons, the error will be removed.

Conclusion

We have seen what a radio button is, the difference between a radio button and checkbox, how to configure material design in angular, and then how to use the angular material radio button, and how to validate the radio button in angular.

Finally, Angular Radio Button Example Tutorial is over.

Leave A Reply

Your email address will not be published.

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