Angular Material 13 Dialog or Modal Popup Tutorial

This Angular material tutorial will show you how to integrate Modal Dialog in the Angular app using the Angular Material dialog UI component.

We will give you the code examples of how to open the material dialog by clicking on the button and how to close or hide the modal popup when the user wants.

We are creating this handy guide for Angular 13, but that doesn’t mean it won’t work with the backward versions; you may use this material dialog implementation guide with Angular 12, 11, 10, 9, 8 till version 7.

We will cover the details that consist of updating the position of a modal or dialog and showing a fullscreen dialog or modal popup. Give you the precise demonstration of multiple events and properties that manage the visibility of material dialog in Angular.

Not just that, you will also find out in this angular material dialog example how to dynamically pass the data to modal and receive data back in Angular’s parent component.

What is Dialog or Modal Popup in UI?

Modal is a significant user interface component; the main use case of modal popup or dialog is to show critical information over every web page element. It grabs the user’s attention and forces them to take appropriate action without hurting the overall user experience.

How to Integrate Modal Popup or Dialog in Angular 13 using Angular Material

  • Step 1: Install Angular Project
  • Step 2: Add Angular Material Module
  • Step 3: Build Material Modules File
  • Step 4: Create Full Screen Modal Popup
  • Step 5: Change Material Dialog Position
  • Step 6: Complete Dialog Structure
  • Step 7: Bind Callback Methods with Dialog
  • Step 8: Run Angular Application

Install Angular Project

Make sure to have Angular CLI installed on your development machine, you may use the given command to install the tool.

npm install -g @angular/cli

Execute the following command to create a new angular demo application.

ng new ng-material-demo

After the app is installed, directly get into the app folder.

cd ng-material-demo

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, therefore, you need to update the compilerOptions and angularCompilerOptions in tsconfig.json file for disabling the strict mode:

{
   “strict”: false, 
   "noImplicitReturns": false 
   "strictTemplates": false
}

Add Angular Material Module

Run the suggested command to install the angular material library from ng source.

ng add @angular/material

To configure the material style select the given options from your terminal window:

  1. Choose a prebuilt theme name or “custom” for a custom theme:

    You can choose from prebuilt material design themes or set up an extensible custom theme.

  2. Set up global Angular Material typography styles:

    Whether to apply the global typography styles to your application.

  3. Set up browser animations for Angular Material:

    Importing the BrowserAnimationsModule into your application enables Angular’s animation system. Declining this will disable most of Angular Material’s animations.

Open the src/styles.scss file, in this file you have to import the material styling CSS link:

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

Build Material Modules File

Create src/material.module.ts file and import all the material design modules in this single file.

It is not necessary to import all the modules because we only need MatDialogModule but it is good to keep all the modules in case of implementing other material module.

import { NgModule } from '@angular/core';
import { A11yModule } from '@angular/cdk/a11y';
import { CdkAccordionModule } from '@angular/cdk/accordion';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PortalModule } from '@angular/cdk/portal';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { CdkStepperModule } from '@angular/cdk/stepper';
import { CdkTableModule } from '@angular/cdk/table';
import { CdkTreeModule } from '@angular/cdk/tree';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule, MatRippleModule } from '@angular/material/core';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';
import { OverlayModule } from '@angular/cdk/overlay';

@NgModule({
  exports: [
    A11yModule,
    CdkAccordionModule,
    ClipboardModule,
    CdkStepperModule,
    CdkTableModule,
    CdkTreeModule,
    DragDropModule,
    MatAutocompleteModule,
    MatBadgeModule,
    MatBottomSheetModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatNativeDateModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatSortModule,
    MatTableModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
    MatTreeModule,
    OverlayModule,
    PortalModule,
    ScrollingModule,
  ],
})

export class MaterialModule {}

Add the CUSTOM_ELEMENTS_SCHEMA, FormsModule, ReactiveFormsModule and MaterialModule modules in app/app.module.ts file.

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

import { BrowserModule } from '@angular/platform-browser';

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

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MaterialModule } from '../material.module';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})

export class AppModule {}

Create Full Screen Modal Popup

You can create the fullscreen modal dialog easily by setting up the custom width, height and CSS, although the default dialog width is 80 percent.

this.dialog.open(MatDialogComponent,
      {
        data: this.myModalInfo,
        panelClass: 'modal-fullscreen',
        height: '100vh',
        width: '100%'
      }
    );

In the open method, we declare the panel class, height and width. Make sure to add the custom css property in css tempalte.

.modal-fullscreen {
  max-width: 100% !important;
}

Change Material Dialog Position

You can update or change modal dialog position, top, bottom, right and left; you have to define the position prop for adjusting the position of dialog.

const modalDialog = this.dialog.open(MatDialogComponent,
      {
        data: this. myModalInfo,
        position: {
          left: '55px',
          top: '55px',
        }
      }
    );

Complete Dialog Structure

The dialog HTML structure consists of a header, body and footer panel; here is an example that demonstrates how to add the header, footer and body panel in the dialog.

<h2 mat-dialog-title>Angular Dialog Example</h2>
<mat-dialog-content class="mat-typography">
  <h3>Material Design Supremacy</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras aliquet nulla nulla, eu euismod tellus dictum.</p>
</mat-dialog-content>
<mat-dialog-actions align="end">
  <button mat-button mat-dialog-close>Cancel</button>
  <button mat-button [mat-dialog-close]="true" cdkFocusInitial>Install</button>
</mat-dialog-actions>

Bind Callback Methods with Dialog

Open the mat-dialog.component.html file, add the given code in the file.

<h5>Do you agree?</h5>
<p>This might occur...{{fromWebPage}}</p>
<button mat-button color="warn" (click)="modalDialogYes()">Yes</button>
<button mat-button color="primary" (click)="modalDialogNo()">No</button>
<button mat-button (click)="modalDialogMaybe()">Maybe</button>

Head over to mat-dialog.component.ts, and update the provided code in the file.

export class MatDialogComponent implements OnInit {
  fromWebPage!: string;
  fromWebDialog!: string;

  constructor(
    public dialogRef: MatDialogRef<MyDialogComponent>,
    @Optional() @Inject(MAT_DIALOG_DATA) public myCustomData: any
  ) {}

  ngOnInit(): void {
    this.fromWebPage = this.myCustomData;
    this.fromWebDialog = "Came from modal...";
  }

  modalDialogYes() {
    this.dialogRef.close({ event: "yes-prop", data: this.fromWebDialog });
  }
  modalDialogNo() {
    this.dialogRef.close({ event: "no-prop", data: this.fromWebDialog });
  }
  modalDialogMaybe() {
    this.dialogRef.close({ event: "maybe-prop", data: this.fromWebDialog });
  }
}

You have to then define the given dialog display method in main AppModule class.

showConfirmModal() {
    const modalDialogComp = this.dialog.open(MatDialogComponent,
      {
        data: 'Your data might be gone forever!'
      }
    );

    modalDialogComp.afterClosed().subscribe((response) => {
      switch (response.event) {
        case "yes-prop":
          console.log('Clicked on Yes');
          break;
        case "no-prop":
          console.log('Clicked on No');
          break;
        case "maybe-prop":
          console.log('Clicked on Myabe');
          break;

        default:
          break;
      }
    });
  }

Run Angular Application

Start the development server through the execution of following command.

ng serve

Type the following url on the address bar and hit enter to view the app.

http://localhost:4200

Angular Material 13 Dialog or Modal Popup Tutorial

Conclusion

We have reached the end of this guide; we have learned how to implement Material dialog in an Angular app easily.

We covered essential details such as opening and closing the dialog, passing the data to the material modal, show and hiding dialog using material dialog properties and options. We have also talked about how to customize modal dialog styling using custom CSS.