Angular Material Dialog Modal: A Complete Example

Angular Material Modal is a built-in module filled with significant, modern UI components that work across the web, mobile, and desktop applications. The MatDialog service can open modal dialogs with Material Design styling and animations.

Here is the step-by-step guide to implement the material dialog modal in Angular.

Step 1: Create an Angular Project

Type the following command.

ng new angularmodal

Angular Material Modal

Step 2: Install Angular Material Libraries.

Go inside the project folder and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is an optional dependency and helps with touch support for a few components.

Install Angular Material and Angular Animations using the following command.

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

Include hammerjs inside an angular.json file. You can find this file at the root of the angular project.

Step 3: Create the Custom Material Module File.

Inside the src >> app folder, create one module file called material.module.ts. We have created this material.module.ts file separately because, in the future, we can import the different Material components in this file, which we will import inside the app.module.ts file.

// material.module.ts

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

import { MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';

@NgModule({
  exports: [FormsModule, MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule]
})
export class MaterialModule {}

We imported the only FormsModule from Angular FormsMatDialogModule, MatFormFieldModule, MatInputModule, and MatButtonModule components from the Angular Material Library.

Step 4: Import a pre-built theme and Material icons

Angular Material comes with some pre-built themes. These themes provide us with set-off colors and basic styling.

The main available themes are indigo-pinkdeeppurple-amberpurple-green, and pink-bluegrey. To import the theme into our project, we can add the following code to your global styles.css file. The file is inside the src folder.

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

You can also access the Material Design icons and use these named icons with the <mat-icon> component.

To import them to your project, you can add this to the head section of your project’s root index.html file.

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

The final step is to import material.module.ts and other angular materialmodulese and BrowserAnimationsModule files inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, BrowserAnimationsModule, MaterialModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 5: Angular Material Modal Implementation.

The MatDialog service can open modal dialogs with Material Design styling and animations.

Create inside the app.component.ts file, and write the following code.

// app.component.ts

import { Component, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { DialogData } from './DialogData';

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

}

Create an interface called DialogData.ts file inside the src >> app folder. Then, write the following code inside that file.

// DialogData.ts

export interface DialogData {
  animal: string;
  name: string;
}

Create an Angular Component by typing the following command.

ng g c modal --module app --spec=false

It will create a modal-component folder inside the app folder.

Write the following code inside the modal.component.ts file.

// modal.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { DialogData } from '../DialogData';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  constructor(
    public dialogRef: MatDialogRef<ModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

  ngOnInit() {
  }

}

ModalComponent.ts class is the actual class that implements the Angular Material Modal.

The modalComponent class accepts the DialogData and displays it inside the dialog. We have used the Dependency Injection to inject the data inside the Angular Dialog.

Write the HTML file of ModalComponent inside the modal.component.html file.

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

We have used the Material Modules and Angular Form modules in this HTML file, which we imported earlier inside the material.module.ts file.

Above HTML will be shown when a user clicks on the button that pops up the Modal.

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

// app.component.ts

import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ModalComponent } from './modal/modal.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  animal: string;
  name: string;

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    const dialogRef = this.dialog.open(ModalComponent, {
      width: '250px',
      data: {name: this.name, animal: this.animal}
    });

    dialogRef.afterClosed().subscribe(result => {
      this.animal = result;
    });
  }
}

First, we imported the ModalComponent inside the app.component.ts file.

Then we created one function called openDialog(), which will open the ModalComponent.

We passed the data like name and animal to that ModalComponent.

When the user closes the ModalComponent, AppComponent gets the value of the animal, which we have typed inside the ModalComponent and displayed inside the AppComponent file.

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

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

Our final app.component.ts file looks like the one below.

// app.component.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';
import { ModalComponent } from './modal/modal.component';

@NgModule({
  declarations: [AppComponent, ModalComponent],
  imports: [BrowserModule, BrowserAnimationsModule, MaterialModule],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [ModalComponent]
})
export class AppModule {}

Finally, save the file and start the angular dev server with the following command.

ng serve --open

It will open the browser, and you can see something like below.

Angular Material Modal Implementation.

First, type your name and click the button; pick one, and you will see the Angular Material Dialog.

Angular Modal Tutorial With Example | Angular Material Dialog

If you press the Ok and have typed the animal name, you will see something like below.

Angular Modal Tutorial With Example

That’s it for this tutorial.

Github Code

8 thoughts on “Angular Material Dialog Modal: A Complete Example”

  1. This was really helpful. It fills the gap between the Angular Material site, which doesn’t provide a worked example, by providing a step-by-step example that works from scratch

    Reply
  2. Hi, I get the problem
    modal.component.ts(14,6): error TS2304: Cannot find name ‘Inject’.
    any idea.
    Specs:
    Angular CLI: 8.0.6
    Node: 10.9.0
    OS: darwin x64
    Angular: 8.0.3

    Reply
  3. First, this is a wonderful article on a complex subject.
    However, there are two areas that need adjustment for Angular 13:
    The Angular declarations in app.component.ts and the Angular/material module imports.
    I have made the changes and have published them on github at penMANship/Angular13-Material-Modal.

    I am grateful for your article and look forward to many more by you.

    Reply
  4. Hi

    I’m not that successfull 🙁
    I’m working with Angular 14.
    I did “ng new angularmodal” which went fine.
    I did “npm install –save hammerjs” which went fine.
    I did “npm install –save @angular/material @angular/animations @angular/cdk” which aborted and suggested to use force so I did “npm install –force @angular/material @angular/animations @angular/cdk” which passed with warnings.
    You wrote “Now, include hammerjs inside an angular.json file.”. I know where the file is I just don’t know how to do the include so I did not.
    Now I started copying what you wrote and I got to the point of app.module.ts. Here when I added “import { MaterialModule } from ‘./material.module’;” and saved I got many errors. The first one of them being – “Error: node_modules/@angular/cdk/a11y/index.d.ts:152:18 – error TS2707: Generic type ‘ɵɵDirectiveDeclaration’ requires between 6 and 8 type arguments.

    152 static ɵdir: i0.ɵɵDirectiveDeclaration;”
    I don’t know how to proceed and would appreciate some help.
    Thanks
    Moshik

    Reply

Leave a Comment

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