AppDividend
Latest Code Tutorials

Angular 9/8/7 Material Checkbox Example For Beginners

0

Angular material checkbox is an inbuilt material component that provides the same functionality as a native <input type=”checkbox”> enhanced with Material Design styling and animations. In the Material Checkbox module, there are three states.

  1. Checked and
  2. Unchecked
  3. Indeterminate

Indeterminate Checkbox state indicates that some of the checkbox items are checked, but not all. It is shown with a hyphen (-) in the checkbox.

Angular 9 Material Checkbox

In this tutorial, we will create a list of cartoons that a user can check to uncheck.

After submit the form, we will get the values of the selected checkbox in an array.

If you want to work with primary checkbox, then check out: Angular checkbox example

To work with an angular material checkbox, we need to import MatCheckboxModule.

Okay, now let’s start our Angular 9 checkbox tutorial from scratch.

Step 1: Create an Angular 9 Application

Run the following npm command to create a new project using ng CLI.

ng new ang

Now, go to the project directory and open the project inside the visual studio code.

code .

Step 2: Install Angular Material 8

Run the following NPM command to install Angular Material, and it’s dependencies.

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

Step 3: Configure Material Animations

Open the app.module.ts file to import BrowserAnimationsModule then adds it inside the imports array to enable animation for Material components.

// app.module.ts

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

imports: [
    ...
    BrowserAnimationsModule
  ],

Step 4: Add Material Theme

We can add the theme of Material in the project by opening the styles.css file then import one of the theme files used to style Material components.

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

Also, add the hammer.js using the following command.

npm install --save hammerjs

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"
]

Let’s import the material icons by adding the following CSS link inside the index.html file.

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

Step 5: Create a separate material module file

Now, create a custom material.module.ts file inside the src >> app folder and add the following code.

// material.module.ts

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

import {
  MatCheckboxModule,
  MatFormFieldModule,
  MatInputModule,
  MatCardModule,
  MatButtonModule
} from '@angular/material';

@NgModule({
  imports: [
    MatCheckboxModule,
    MatFormFieldModule,
    MatInputModule,
    MatCardModule,
    MatButtonModule
  ],
  exports: [
    MatCheckboxModule,
    MatFormFieldModule,
    MatInputModule,
    MatCardModule,
    MatButtonModule
  ]
})

export class MaterialModule { }

To use the Material component, we need to import it into the app’s module. Here for our Checkbox module, we will import some other modules.

  1. MatCheckboxModule: Checkbox component module <mat-checkbox>
  2. MatInputModule: The matInput is a directive that allows native <input> and <textarea> elements to work with <mat-form-field>.
  3. MatFormFieldModule: The <mat-form-field> is a component used to wrap several Angular Material components and apply common Text field styles such as the underline, floating label, and hint messages.
  4. MatCardModule: Card module that will wrap Checklist in a card <mat-card>
  5. MatButtonModule: Button module, will help to submit the form <mat-button>

Step 6: Import material module inside app module.

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

// 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 { }

We have imported MaterialModule for material design components.

Then we have imported FormsModule and ReactiveForms module to deal with Angular forms.

Step 7: Define a list of cartoons

Inside the app.component.ts file, write the following code.

// app.component.ts

export interface Cartoon {
  id: number;
  name: string;
}

export class AppComponent implements OnInit {
cartoonsData: Cartoon[] = [
    { id: 0, name: 'Tom and Jerry' },
    { id: 1, name: 'Rick and Morty' },
    { id: 2, name: 'Ben 10' },
    { id: 3, name: 'Batman: The Animated Series' }
  ];
}

We have exported an interface called Cartoon. So our cartoonsData array is the type of Cartoon.

We will render the cartoonsData list into the material form and create a checkbox one by one using Angular ngFor directive.

Step 8: Define FormControl and FormGroup

Okay, now let’s design the engine of our application, which is the app.component.ts file.

First, write the following code inside the app.component.ts file, and then we will see what we have written in the code.

// app.component.ts

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

export interface Cartoon {
  id: number;
  name: string;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  form: FormGroup;
  cartoonsData: Cartoon[] = [
    { id: 0, name: 'Tom and Jerry' },
    { id: 1, name: 'Rick and Morty' },
    { id: 2, name: 'Ben 10' },
    { id: 3, name: 'Batman: The Animated Series' }
  ];

  constructor(private fb: FormBuilder) { }

  onChangeEventFunc(name: string, isChecked: boolean) {
    const cartoons = (this.form.controls.name as FormArray);

    if (isChecked) {
      cartoons.push(new FormControl(name));
    } else {
      const index = cartoons.controls.findIndex(x => x.value === name);
      cartoons.removeAt(index);
    }
  }

  ngOnInit() {
    this.form = this.fb.group({
      name: this.fb.array([])
    });
  }

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

}

First, we have imported various angular forms modules.

Then we have created a form builder instance.

Next, we have defined the onChange event of the checkbox.

When the user selects the checkbox, we will get the checked value and name of that checkbox.

We will store it inside the array if the user checks the value; otherwise, we remove the value from the array.

When the user submits the form, we will get the array of checked values.

Step 9: Create HTML Checkbox view

To create an HTML view, we will use the Material card component, Material checkbox component, and Material button component.

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

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

<mat-card>
<mat-card-content>
  <h2 class="example-h2">Angular Material Checkbox Example</h2>
   <form [formGroup]="form" (ngSubmit)="submit()">
    <section class="example-section" *ngFor="let cartoon of cartoonsData">
      <mat-checkbox class="example-margin"
          (change)="onChangeEventFunc(cartoon.name, $event)">
      {{ cartoon.name }}
      </mat-checkbox>
    </section>
    <button mat-raised-button color="accent">Submit</button>
   </form>
</mat-card-content>
</mat-card>

Save the file and go to the browser and run the project using the following command.

ng serve -o

The project will open at http://localhost:4200

Angular 8 Material Checkbox Example

 

From the output, you can see that we have checked two checkbox values, and we get the array of those values inside the console.

You can find this code on the Github repository. Please, after cloning the repository, do not forget to run npm install to install all the third-party libraries.

Conclusion

In this tutorial, we have seen how to install and setup material design in Angular and how to import various material modules, and how to create material checkbox form, and how to get the checked values of the checkbox.

Finally, Angular 9/8/7 Material Checkbox Example is over.

GITHUB CODE

Leave A Reply

Your email address will not be published.

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