Add Dialog Component from Angular Material

  1. Install @angular/material by npm command.
  2. Create a new component by ng g c command.
  3. Assume the name of the new component is AlertDialogComponent, and it only display an alert message with an OK button. The TS file would be: (Note: this constructor take a data parameter)
    import {Component, Inject} from '@angular/core';
    import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
      selector: 'app-alert-dialog',
      templateUrl: './alert-dialog.component.html',
      styleUrls: ['./alert-dialog.component.css']
    export class AlertDialogComponent {
      constructor(public dialogRef: MatDialogRef<AlertDialogComponent>,
                  @Inject(MAT_DIALOG_DATA) public data: any) {
      onOKClick(): void {
  4. The HTML file would be:
    <div mat-dialog-content>
    <div mat-dialog-actions>
      <button mat-button style="float: right" class="btn btn-primary"(click)="onOKClick()">OK</button>
  5. Once the component is completed, we need to add it in a module. If this is use in the whole project, import it in the root module.
    import {AlertDialogComponent} from "@app/shared/alert-dialog/alert-dialog.component";
    export const appConfig = {
      declarations: [
      imports: [
      providers: [...],
      bootstrap: [AppComponent]
  6. To use the alert dialog in your component, import it:
    import {AlertDialogComponent} from "@app/shared/alert-dialog/alert-dialog.component";
    import {MatDialog} from "@angular/material";
  7. Then inject a MatDialog in your component constructor:
      constructor(public dialog: MatDialog) {}
  8. To show up the dialog, call this code:
       const dialogRef =, {
         width: '250px',
         data: {message: "OK, Jahaa, sehr gut!"}
  9. Note: we use date.message to pass the message to our alert dialog component. Go back to step 3 and 4, you will see how to dialog get that date.

  1. Do all the thing like the basic dialog
  2. Modify the HTML of your component so that use can do some input, bind that input to a variable in your ts file.
  3. The component that open the dialog should subscribe the dialog afterClosed event as below. The result would be what the dialog component pass to the subscriber
        dialogRef.afterClosed().subscribe(result => {...});
  4. In the dialog component, when you close it, close it with a parameter of any kind you like. that would be what the subscriber receives as the result variable. In the below case, the subscriber will receive a number of 10.
  • ng/add_dialog_component_from_angular_material.txt
  • Last modified: 2019/02/12 08:53
  • by chongtin