Build Modal / Dialog in Angular 13 with Angular Material

Last updated on: by Digamber
In this tutorial, we are going to go through abut Angular 13 Modal with Angular Material Dialog component.

To create a Modal box in Angular web application, we use Angular Material 10 UI library. Angular material UI library offers a wide range of UI components to create real-world web and mobile apps.

Angular Material UI components help us to build robust, consistent, engaging, and user-centric interfaces. Here, we are going to highlight the most common use cases related to Angular 8 Modals.

For the demo purpose, I have taken the help of Angular material dialog component to create an Angular Modal box.

Let us start creating an Angular Modal step by step by following this tutorial.

Angular Material 11 Modal or Dialog Example

  • Closing The Angular material Dialog
  • Configuration of Angular Material Dialog options
  • Passing & Receiving the Data in the Angular Model
  • Implementing Angular Material Dialog in an Angular app
  • Creating an Angular Modal using Angular Material dialog
  • Installation and Configuration of Angular Material project

Install Angular App

Let’s install the Angular project to show the Angular Modal demo with Angular Material Dialog.

ng new angular-material-dialog
# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? SCSS

Go inside project folder.

cd angular-material-dialog

Configure Angular Material 11 Library

Use the following command to install and configure Material library in Angular Modal project:

ng add @angular/material

In the next step, we are going to have a look at Angular Material pre-built themes.

Angular Material offers following pre-built themes deeppurple-amber, indigo-pink, purple-green and pink-bluegrey.

To set up any of the given pre-built Material theme, we have to choose among the given options and Angular CLI will automatically ad the theme in your styles.css file.

Choose Angular Material Pre-built Theme from the following options:

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink
❯ Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ] 
  Deep Purple/Amber  [ Preview: https://material.angular.io?theme=deeppurple-amber ] 
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey ] 
  Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]
# ? Set up global Angular Material typography styles? Yes
# ? Set up browser animations for Angular Material? Yes

Check out the full Angular Material documentation here.

Create Custom Angular Material Module File

Now, we are going to create a custom angular-material.module.ts file, in this file we will import the following Angular material ui components from the Angular Material library.

  • MatDialogModule
  • MatFormFieldModule
  • MatInputModule
  • MatButtonModule

Go to angular-material.module.ts file and add the following code.

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import {MatDialogModule} from '@angular/material/dialog';

const materialModules = [
  MatButtonModule,
  MatIconModule,
  MatFormFieldModule,
  MatInputModule,
  MatDialogModule
];
@NgModule({
  imports: [
    CommonModule,
    ...materialModules
  ],
  exports: [
    ...materialModules
  ],
})
export class AngularMaterialModule { }

Integrating Angular Modal using Angular Material Dialog

Now, we are going to generate my-modal component, using the following command.

ng g c my-modal

Add the given below code in the my-modal.component.ts file.

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { ModalData } from '../model-data';
@Component({
  selector: 'app-my-modal',
  templateUrl: './my-modal.component.html',
  styleUrls: ['./my-modal.component.css']
})
export class MyModalComponent implements OnInit {
  constructor(
    public dialogRef: MatDialogRef<MyModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: ModalData) 
  { }
  onNoClick(): void {
    this.dialogRef.close();
  }
  ngOnInit() {
  }
}

Go to my-modal.component.html file and add the following code in it.

<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
  <p>What's your favorite color?</p>
  <mat-form-field>
    <input matInput [(ngModel)]="data.color">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data.color" cdkFocusInitial>Ok</button>
</div>

Then, in this step we are going to inject MyModalComponent inside the entryComponents array in the app module file. This is also the final version of our app.module.ts file, kindly compare it with your code.

import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
/* Angular material */
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material.module';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { MyModalComponent } from './my-modal/my-modal.component';
@NgModule({
  declarations: [
    AppComponent,
    MyModalComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AngularMaterialModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  entryComponents: [MyModalComponent]
})
export class AppModule { }

In this step, we are going to use MatDialog service, and this service helps to open the Angular Modal with Material dialogs.

Now, head over to app.component.ts file, add the following code.

import { Component } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { MyModalComponent } from './my-modal/my-modal.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string;
  color: string;
  constructor(public dialog: MatDialog) { }
  openDialog(): void {
    const dialogRef = this.dialog.open(MyModalComponent, {
      width: '250px',
      data: { name: this.name, color: this.color }
    });
    dialogRef.afterClosed().subscribe(res => {
      this.color = res;
    });
  }
}

As you can see the MatDialogRef Angular Material service provides an option to close the opened Angular Modal box.

Finally, go to app.component.html file, include the given below code.

<div>
  <mat-form-field>
    <input matInput [(ngModel)]="name" placeholder="What's your favorite color?">
  </mat-form-field>
</div>
<div>
  <button mat-raised-button (click)="openDialog()">Pick one</button>
</div>
<h4 *ngIf="color">
  You selected: <p style="font-weight: bold">{{color}}</p>
</h4>

Finally, we have shown you how to create an overlay Modal box in Angular 11 using Angular Material Dialog UI component service. I hope this tutorial has helped you learn the Angular Material Modal concept.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.