How to Create Toggle Button in Angular with Angular Material 13

In this quick article, we will demonstrate how to create simple toggle buttons in the Angular application. To build toggle buttons in angular, we will use the profound angular material library.

You will be given code examples of various types of toggle buttons using the mat-button-toggle-group attribute.

Ideally, the mat-button-toggle property is used to invoke on/off toggles with resemblance to a normal button. Buttons are used for performing an action to solve some purpose on a web or mobile app.

Toggle buttons are set up using an angular environment, either using the checkboxes or radio buttons. The mat-button-toggle-group directive completes the forming of toggle buttons in angular.

Angular Material 13 Toggle Buttons Example

  • Step 1: Build Angular Project
  • Step 2: Install Material Library
  • Step 3: Import Material Modules
  • Step 4: Create Basic Toggle Buttons
  • Step 5: Single / Multiple Toggle Buttons Selection
  • Step 6: Toggle Buttons with Template Driven and Reactive Forms
  • Step 7: Start Angular App

Build Angular Project

Before you start developing angular app, make sure to install the Angular CLI tool in your development machine.

npm install -g @angular/cli

Now, you can easily create the latest angular application using the given command:

ng new ng-material-demo

Move into the angular app folder using given command:

cd ng-material-demo

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, therefore, you need to update the compilerOptions and angularCompilerOptions in tsconfig.json file for disabling the strict mode:

{
   “strict”: false, 
   "noImplicitReturns": false 
   "strictTemplates": false
}

Install Material Library

Next step is to add the material design library in our angular project, ensure that you invoke the given command.

ng add @angular/material

You have to choose the given options from the terminal to configure the material theme, typography and animations.

  1. Choose a prebuilt theme name or “custom” for a custom theme:

    You can choose from prebuilt material design themes or set up an extensible custom theme.

  2. Set up global Angular Material typography styles:

    Whether to apply the global typography styles to your application.

  3. Set up browser animations for Angular Material:

    Importing the BrowserAnimationsModule into your application enables Angular’s animation system. Declining this will disable most of Angular Material’s animations.

In the src/styles.scss file, define the material theme css to rapidly design the ui components.

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

Import Material Modules

We will make material.module.ts file in src/ folder, thereafter import MatButtonToggleModule along with all the material component modules.

import { NgModule } from '@angular/core';
import { A11yModule } from '@angular/cdk/a11y';
import { CdkAccordionModule } from '@angular/cdk/accordion';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PortalModule } from '@angular/cdk/portal';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { CdkStepperModule } from '@angular/cdk/stepper';
import { CdkTableModule } from '@angular/cdk/table';
import { CdkTreeModule } from '@angular/cdk/tree';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule, MatRippleModule } from '@angular/material/core';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';
import { OverlayModule } from '@angular/cdk/overlay';

@NgModule({
  exports: [
    A11yModule,
    CdkAccordionModule,
    ClipboardModule,
    CdkStepperModule,
    CdkTableModule,
    CdkTreeModule,
    DragDropModule,
    MatAutocompleteModule,
    MatBadgeModule,
    MatBottomSheetModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatNativeDateModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatSortModule,
    MatTableModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
    MatTreeModule,
    OverlayModule,
    PortalModule,
    ScrollingModule,
  ],
})

export class MaterialModule {}

Head over to app.module.ts file, and import CUSTOM_ELEMENTS_SCHEMA, FormsModule, ReactiveFormsModule and MaterialModule modules.

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MaterialModule } from '../material.module';

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

export class AppModule {}

Create Basic Toggle Buttons

Use the mat-button-toggle-group directive to make the simple grouped toggle buttons; the following code directly goes into the angular HTML template.

<mat-button-toggle-group name="fontStyle" aria-label="Font Style">
  <mat-button-toggle value="bold">Bold</mat-button-toggle>
  <mat-button-toggle value="italic">Italic</mat-button-toggle>
  <mat-button-toggle value="underline">Underline</mat-button-toggle>
</mat-button-toggle-group>

Single / Multiple Toggle Buttons Selection

We can change the toggle button selection process from single to multiple by using the multiple property; make sure to add this property in the mat-button-toggle-group.

<h3>Single Toggle Selection</h3>
<mat-button-toggle-group name="favoriteColor" aria-label="Favorite Color">
  <mat-button-toggle value="red">Red</mat-button-toggle>
  <mat-button-toggle value="green">Green</mat-button-toggle>
  <mat-button-toggle value="blue">Blue</mat-button-toggle>
</mat-button-toggle-group>

<h3>Multiple Toggle Selection</h3>
<mat-button-toggle-group name="ingredients" aria-label="Ingredients" multiple>
  <mat-button-toggle value="flour">Flour</mat-button-toggle>
  <mat-button-toggle value="eggs">Eggs</mat-button-toggle>
  <mat-button-toggle value="sugar">Sugar</mat-button-toggle>
</mat-button-toggle-group>

Toggle Buttons with Template Driven and Reactive Forms

Angular offers template driven and reactive form api to handle form data, and you can use material toggle buttons with both the forms api.

Update the code in app.component.html file.

<section>
  <h4>Button Toggle inside of a Template-driven form</h4>
  <mat-button-toggle-group [(ngModel)]="fontStyle" aria-label="Font Style">
    <mat-button-toggle value="bold">Bold</mat-button-toggle>
    <mat-button-toggle value="italic">Italic</mat-button-toggle>
    <mat-button-toggle value="underline">Underline</mat-button-toggle>
  </mat-button-toggle-group>
  <p>Chosen value is {{fontStyle}}</p>
</section>

<section>
  <h4>Button Toggle inside of a Reactive form</h4>
  <mat-button-toggle-group [formControl]="fontStyleControl" aria-label="Font Style">
    <mat-button-toggle value="bold">Bold</mat-button-toggle>
    <mat-button-toggle value="italic">Italic</mat-button-toggle>
    <mat-button-toggle value="underline">Underline</mat-button-toggle>
  </mat-button-toggle-group>
  <p>Chosen value is {{fontStyleControl.value}}</p>
</section>

Next, add the code in app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

export class AppComponent {
  fontStyleControl = new FormControl();
  fontStyle?: string;
}

Start Angular App

We are done with the code examples, next step is to start the angular application.

ng serve

After you serve the above command open the given url in the browser to test the app.

http://localhost:4200

How to Create Toggle Button in Angular with Angular Material 13

Conclusion

In this eloquent tutorial, we showed you the example of angular material mat-button-toggle.

By using this essential property, we learned how to add simple toggle buttons in the angular component; you can bind any event to the toggle button and solve your programming purpose.