Angular Material - CheckBox



The <mat-checkbox>, an Angular Directive, is used as a enhanced checkbox with material design styling and animation capabilities.

In this chapter, we will showcase the configuration required to draw a checkbox control using Angular Material.

Create Angular Application

Follow the following steps to update the Angular application we created in Angular Material - First Application chapter −

Step Description
1 Create a project with a name material-app as explained in the Angular Material - First Application chapter.
2 Modify app.ts, app.css and app.html as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

app.ts

Following is the content of the modified app.ts.

import { Component, model, OnInit, signal } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatCheckboxModule } from '@angular/material/checkbox';

@Component({
   selector: 'app-root',
   imports: [
      FormsModule,
      MatFormFieldModule,
      MatInputModule,
      MatCheckboxModule,
      ReactiveFormsModule,
   ],
   templateUrl: './app.html',
   styleUrl: './app.css'
})
export class App {
   protected readonly title = signal('material-app');

   readonly checked = model(false);
   readonly indeterminate = model(false);
   readonly labelPosition = model<'before' | 'after'>('after');
   readonly disabled = model(false);
}

app.html

Following is the content of the modified HTML host file app.html.

<h2 class = "tp-h2">Checkbox configuration</h2>
<section class = "tp-section">
   <mat-checkbox class = "tp-margin" [(ngModel)] = "checked">Checked</mat-checkbox>
   <mat-checkbox class = "tp-margin" [(ngModel)] = "indeterminate">Indeterminate</mat-checkbox>
</section> 
<section class = "tp-section">
   <mat-checkbox class = "tp-margin" [(ngModel)] = "disabled">Disabled</mat-checkbox>
</section>
<h2 class = "tp-h2">Result</h2>
<section class = "tp-section">
   <mat-checkbox
      class = "tp-margin"
      [(ngModel)] = "checked"
      [(indeterminate)] = "indeterminate"
      [labelPosition] = "labelPosition()"
      [disabled] = "disabled()">
      Sample Checkbox
   </mat-checkbox>
</section>

app.css

Following is the content of the modified CSS file app.css.

.tp-h2 {
   margin: 10px;
}
.tp-section {
   display: flex;
   align-content: center;
   align-items: center;
   height: 60px;
}
.tp-margin {
   margin: 0 10px;
}

Result

Verify the result.

Checkbox

Details

  • As first, we've created three check boxes using mat-checkbox and bind them using ngModel with variables.

  • Then, we've created another checkbox and showcased its various attributes bound with variables in .ts file.

Advertisements