Angular 8 Modal Tutorial with Angular Material Dialog

By Digamber Rawat Last updated on
In this tutorial, we are going to go through abut Angular 8 Modal with Angular Material Dialog component. To create a Modal box in Angular 8 web application, we use Angular material 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 8 Dialog Topics:

  • 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

#01 – Angular 8 Modal Tutorial with Angular Material Dialog

Let’s install the Angular 8 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

#02 – Install & Configure Angular Material 8 UI Library

Use the following command to install and configure Angular Material 8 UI library in our Angular 8 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 HammerJS for gesture recognition? (Y/n) = Y
# ? Set up browser animations for Angular Material? (Y/n) = Y

Check out the full Angular Material 8 documentation here.

#03 – 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: MatDialogModule, MatFormFieldModule, MatInputModule, and MatButtonModule from the Angular Material library.

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

import { NgModule } from '@angular/core';
import {
    MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule
} from '@angular/material';


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

export class AngularMaterialModule { }

Import Angular Material module file inside the app.module.ts file.

/* Angular material */
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material.module';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [...],
  imports: [
    BrowserAnimationsModule,
    AngularMaterialModule,
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

export class AppModule { }

#04 – 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 app > 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 8 using Angular Material Dialog UI component service. I hope this tutorial has cleared your doubts, however, if you have missed anything, you can check out the GitHub repo here.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.