Angular Material 13 Checkboxes with Reactive Forms Tutorial

Angular Material 13 Checkboxes example. In this guide, we will elaborate how to create and use Angular Material Checkboxes in Angular application.

To create the checkboxes in angular we will import and use MatCheckboxModule that we will gather from Angular Material library.

The MatCheckbox is a material design checkbox component; it supports all the features of an HTML 5 Checkbox and provides an identical API. We can set the mat checkbox state to checked, unchecked, indeterminate, and even disabled.

We will show you how to create an essential checkbox component in angular, show you how to create an indeterminate checkbox in angular, and show you how to use the checkbox component with Reactive forms API.

How to Implement Angular Material Checkboxes in Angular 13 Application

  • Step 1: Create Angular Project
  • Step 2: Install Angular Material Module
  • Step 3: Set Up Material Module File
  • Step 4: Create checkboxes Component
  • Step 5: Create Checkboxes with Reactive Form
  • Step 6: View App on Browser

Create Angular Project

To start developing angular app you must install the latest stable version of Angular CLI in your machine.

npm install -g @angular/cli

By using angular CLI, you can now easily create a new angular project.

ng new ng-material-demo

Use the command to get into the project folder.

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 Angular Material Module

Execute the following command and install the angular material module in your angular application.

ng add @angular/material

After you executed the command, some questions will appear on terminal window make sure to answer them using the given references.

  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.

Open the src/styles.scss file, inside here you have to add the material CSS as given below.

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

Set Up Material Module File

We now have to create a src/material.module.ts file, in this file import MatCheckboxModule module along with that we will also import all the material 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/app.module.ts file, in here we will be adding the material module and also import CUSTOM_ELEMENTS_SCHEMA, FormsModule, and ReactiveFormsModule.

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 Simple Checkbox

The mat-checkbox directive needs to be added to the angular template to create the simple checkbox.

<section class="example-section">
  <mat-checkbox class="example-margin">Simple Checkbox</mat-checkbox>
</section>

To build the Indeterminate checkbox in angular using angular material, we will have to add the following code in app.component.html file.

<section class="example-section">
  <span class="example-list-section">
    <mat-checkbox
      class="example-margin"
      [checked]="allComplete"
      [color]="task.color"
      [indeterminate]="someComplete()"
      (change)="setAll($event.checked)"
    >
      {{ task.name }}
    </mat-checkbox>
  </span>
  <span class="example-list-section">
    <ul>
      <li *ngFor="let subtask of task.subtasks">
        <mat-checkbox
          [(ngModel)]="subtask.completed"
          [color]="subtask.color"
          (ngModelChange)="updateAllComplete()"
        >
          {{ subtask.name }}
        </mat-checkbox>
      </li>
    </ul>
  </span>
</section>

Next, update the given code in app.component.ts file.

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

export interface Task {
  name: string;
  completed: boolean;
  color: ThemePalette;
  subtasks?: Task[];
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  task: Task = {
    name: 'Indeterminate',
    completed: false,
    color: 'primary',
    subtasks: [
      { name: 'Primary', completed: false, color: 'primary' },
      { name: 'Accent', completed: false, color: 'accent' },
      { name: 'Warn', completed: false, color: 'warn' },
    ],
  };

  allComplete: boolean = false;

  updateAllComplete() {
    this.allComplete =
      this.task.subtasks != null &&
      this.task.subtasks.every((t) => t.completed);
  }

  someComplete(): boolean {
    if (this.task.subtasks == null) {
      return false;
    }
    return (
      this.task.subtasks.filter((t) => t.completed).length > 0 &&
      !this.allComplete
    );
  }

  setAll(completed: boolean) {
    this.allComplete = completed;
    if (this.task.subtasks == null) {
      return;
    }
    this.task.subtasks.forEach((t) => (t.completed = completed));
  }
}

Create Checkboxes with Reactive Form

We will use the formGroup directive to gather the value of checkboxes using the mat-checkbox directive. The formControlName directive sets the individual checkbox value.

In your app.component.html file, you have to define the given code.

<section class="example-section" [formGroup]="toppings">
  <h4>Select your toppings:</h4>
  <p><mat-checkbox formControlName="pepperoni">Pepperoni</mat-checkbox></p>
  <p><mat-checkbox formControlName="extracheese">Extra Cheese</mat-checkbox></p>
  <p><mat-checkbox formControlName="mushroom">Mushroom</mat-checkbox></p>
</section>

<section class="example-section" [formGroup]="toppings">
  <h4>You chose:</h4>
  {{toppings.value | json}}
</section>

First, import the FormBuilder, and FormGroup modules from the ‘@angular/forms’ library, inject the FormBuilder in the constructor method then set the form group value in the group() method.;

Add the code in app.component.ts file.

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

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

export class AppComponent {
  toppings: FormGroup;

  constructor(fb: FormBuilder) {
    this.toppings = fb.group({
      pepperoni: false,
      extracheese: false,
      mushroom: false,
    });
  }
}

View App on Browser

We will now start the angular application through the command line, hence execute the given command.

ng serve

Open the browser, type the given url and press enter to view the app on the browser.

http://localhost:4200

Angular Material 13 Checkboxes with Reactive Forms Tutorial

Conclusion

In this quick tutorial, we revealed how to build a checkbox component in angular using the angular material module.

We learned how to make indeterminate checkboxes and use reactive forms api to handle the checkboxes data in angular.