Angular 5 Material Dialog Implementation Example

By Dhiraj Ray, 28 January,2018   8K

This tutorial is about creating and implementing angular material dialog. We will be using angular 5 provided MatDialogModule to create a custom dialog with functionality to share data between dialog components, global configurations, entry components with example codes. In the last tutorial, we created a sample material login application and used browser alert to show error messages. We will be using the same application and integrate MatDialogModule in it to show messages in a single page application.

In the previous implementation, we created a login application using material. We had two components login and user component. Once user is successfully logged in, he was being redirected to user page. All the dialog implementation will be in the login component and hence I am sharing the existing code of login.component.ts here to make our understanding clear.

login.component.ts
import { Component } from '@angular/core';

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

  constructor(private router : Router) {
  }

  username : string
  password : string

  login() : void {
    if(this.username == 'admin' && this.password == 'admin'){
     this.router.navigate(["user"]);
    }else {
      alert("Invalid credentials");
    }
  }
}

MatDialog Configuration

Material provides MatDialog service to open modal dialogs with Material Design styling and animations by using open() method.This method accepts the component that will be loaded in the body of the dialog as content and optional configuration object to define dialog configuration such as height, width, position, data and many more. The complete list of config items can be found in the official website.Once, the dialog is opened, angular provides MatDialogRef that provides reference to it via the MatDialog service. This reference can be used to perform actions on the opened dialog such as closing of the dialog.To get started with the dialog, let us make the necessary configurations first.

1. Import and export MatDialogModule in the existing material.module.ts. This is a separate file that we created to have all the material module.

2. Create entrycomponents in the app.module.tsThis will contain the dialog component. The name of our dialog component will be ErrorDialogComponent that we will be defining is a minute.

entryComponents: [ErrorDialogComponent]

3. Now same component needs to be included into the providers.

MatDialog Implementation

Now let us create the error-dialog.component.html which will loaded inside the dialog content.

<h2 mat-dialog-title>Error</h2>
<mat-dialog-content class="error">{{data.errorMsg}}</mat-dialog-content>
<mat-dialog-actions>
  <button mat-raised-button (click)="closeDialog()">Ok</button>
</mat-dialog-actions>

Here we have data that will be passed as a configuration parameter while opening a component with open(). This can be used to share data with the dialog component.

Now it is time to define the error-dialog.component.ts

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

@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'error-dialog.component.html'
})

export class ErrorDialogComponent {

  constructor(private dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data : any) {

  }

  public closeDialog(){
    this.dialogRef.close();
  }

}

Here we have MatDialogRef injected that we discussed above that provides reference to opened dialog via the MatDialog service. This reference can be used to perform actions on the opened dialog such as closing of the dialog. Similarly we have data that will be injected by the caller and we have closeDialog() which will be called on the button click and it will close the dialog.

The implementation is done for the dialog and whenever we want to open it we can simply call the open() method provided by MatDialog. Following is the method to open the dialog that we implemented above.

showError(error : string) : void {
    this.dialog.open(ErrorDialogComponent, {
      data: {errorMsg: error} ,width : '250px'
    });
  }

In the above code whatever error message we provide that will be displayed in the dialog and also we are passing the width of the dialog as a config parameter. This method will be called whenever an invalid credentials is provided during login.

import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import {ErrorDialogComponent} from "../core/error-dialog.component";
import {MatDialog} from "@angular/material";

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

  constructor(private router : Router, public dialog : MatDialog) {
  }

  username : string
  password : string

  login() : void {
    if(this.username == 'admin' && this.password == 'admin'){
      this.router.navigate(["user"]);
    }else {
      this.showError("Invalid credentials");
    }
  }

  showError(error : string) : void {
    this.dialog.open(ErrorDialogComponent, {
      data: {errorMsg: error} ,width : '250px'
    });
  }
}

Testing Material Dialog

Open the browser and hit http://localhost:4200then following page will be served.

material-login

Now enter invalid credentials and hit Login button then you can see following dialog appears.

angular-material-dialog

Conclusion

In this article we created angular 5 dialog using MatDialog service. In next article we take a look into how to create material table.If you have anything that you want to add or share then please share it below in the comment section.

1. Angular 6 Example

2. Rxjs Tutorial

3. Building Angular Application

4. Angular Data Table Example

5. Angular Material App

If You Appreciate What We Do Here On Devglan, You Should Consider: