Angular Material Dialog Example

By Arvind Rai, November 13, 2022
On this page we will learn to use Material Dialog in Angular Material application.
1. Material Dialog is created using a Component or <ng-template> with mat-dialog-title, mat-dialog-content, mat-dialog-actions and mat-dialog-close directives.
2. The MatDialog service is used to open the dialog.
3. The MatDialogConfig class is the configuration for opening the dialog. The configurations can be height, width, position etc.
4. The MatDialogRef is the reference to a dialog opened via the MatDialog service.
5. To use Material Dialog, we need to import following module in our application module.
import { MatDialogModule } from '@angular/material/dialog'; 
6. The injection tokens used for Dialog are MAT_DIALOG_DATA, MAT_DIALOG_DEFAULT_OPTIONS and MAT_DIALOG_SCROLL_STRATEGY.

1. Technologies Used

Find the technologies being used in our example.
1. Angular 13.1.0
2. Angular Material 13.3.9
3. Node.js 12.20.0
4. NPM 8.2.0

2. Creating Dialog using Component

Here we will create a dialog using component.
1. The Dialog HTML template code is created using following attributes.
mat-dialog-title : Applied to h1, h2 for heading.
mat-dialog-content : Scrollable content for dialog.
mat-dialog-actions : Container for action buttons at the bottom of the dialog.
mat-dialog-close : Used with <button> to close the current dialog.
<div mat-dialog-content>
  <p>Name:
    <mat-form-field appearance="fill">
      <input matInput [(ngModel)]="data.name" placeholder="Enter name">
    </mat-form-field>
  </p>
  <p>City:
    <mat-form-field appearance="fill">
      <input matInput [(ngModel)]="data.city" placeholder="Enter city">
    </mat-form-field>
  </p>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onCancelUserDialog()">Cancel</button>
  <button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
</div> 

2. To access data in the Dialog sent from opener component, we need to use MAT_DIALOG_DATA injection token. Find the .ts code.
constructor(
  public dialogRef: MatDialogRef<UserDialogComponent>,
  @Inject(MAT_DIALOG_DATA) public data: User,
) { }
onCancelUserDialog(): void {
  this.dialogRef.close();
} 

3. Dialog Opener Component

To open a Dialog, Material provides MatDialog service.
1. MatDialog.open : The MatDialog service is used to open dialog. Its methods are open, getDialogById and closeAll.
Find the MatDialog.open Angular doc.
MatDialog.open 
Parameters:
arg1 : ComponentType<T> | TemplateRef<T>
arg2?: MatDialogConfig<D>
Returns:
MatDialogRef<T, R>
The first argument of MatDialog.open is either a Component or a TemplateRef.
Second argument is the instance of MatDialogConfig class.

2. MatDialogConfig : It is the configuration for opening the dialog. Find some of its properties.
data : Data being injected into the child component.
hasBackdrop : Whether the dialog has a backdrop.
height : Height of the dialog.
width : Width of the dialog.
position : The DialogPosition to override position.
autofocus : Where the dialog should focus on open.

Find the .ts code snippet.
constructor(public dialog: MatDialog) { }
openUserDialog() {
  this.dialogRef = this.dialog.open(UserDialogComponent,
    { data: this.user, height: '350px', width: '250px' });

  this.dialogRef.afterClosed().subscribe((result: User) => {
    console.log('The User dialog was closed.');
    console.log(result?.name + ' - ' + result?.city);
  });
} 
To receive the result sent by Dialog in opener component, we need to subscribe Observable retuned by MatDialogRef.afterClosed()
Now find the HTML template code used in our demo.
<button mat-raised-button (click)="openUserDialog()">Pick user</button> 
In Angular 14, we can change the Dialog open/close animation using following properties of MatDialogConfig class.
enterAnimationDuration : Duration of the enter animation.
exitAnimationDuration : Duration of the exit animation.

4. Creating Dialog using <ng-template>

1. In the Dialog opener component, we can create the Dialog using <ng-template>.
<ng-template let-data #myInfoDialog>
  <h2 mat-dialog-title>Information</h2>
  <div mat-dialog-content>
    {{data}}
  </div>
  <div mat-dialog-actions>
    <button mat-button mat-dialog-close>Close</button>
  </div>
</ng-template> 
To access the dialog template code, use @ViewChild decorator.

2. Use MatDialog.open method to open the Dialog and pass the instance of TemplateRef .
@ViewChild('myInfoDialog') infoDialog = {} as TemplateRef<string>;  
myInfo = "Namaste to the world!";
openInfoDialog() {
    this.dialogRef = this.dialog.open(this.infoDialog,
      { data: this.myInfo, height: '200px', width: '250px' });

    this.dialogRef.afterClosed().subscribe(() => {
      console.log('The Info dialog was closed.');
    });
} 

5. Setting Configurations Globally

The Dialog configurations can be set globally by using MAT_DIALOG_DEFAULT_OPTIONS constant.
providers: [
  {provide: MAT_DIALOG_DEFAULT_OPTIONS,
     useValue: { height: '200px', width: '250px', autoFocus: true }}
] 

6. Complete Example

A. Dialog using Component

user-dialog.component.html
<h2 mat-dialog-title>User Detail</h2>
<div mat-dialog-content>
  <p>Name:
    <mat-form-field appearance="fill">
      <input matInput [(ngModel)]="data.name" placeholder="Enter name">
    </mat-form-field>
  </p>
  <p>City:
    <mat-form-field appearance="fill">
      <input matInput [(ngModel)]="data.city" placeholder="Enter city">
    </mat-form-field>
  </p>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onCancelUserDialog()">Cancel</button>
  <button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
</div> 
user-dialog.component.ts
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { User } from './user';

@Component({
  templateUrl: './user-dialog.component.html',
})
export class UserDialogComponent {
  constructor(
    public dialogRef: MatDialogRef<UserDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: User,
  ) { }
  onCancelUserDialog(): void {
    this.dialogRef.close();
  }
} 
B. Dialog Opener Component + Dialog using ng-template

example-dialog.component.html
<h2>Dialog Demo</h2>
<p>
  <button mat-raised-button (click)="openUserDialog()">Pick user</button>
  <br /> {{user.name}}
  <br /> {{user.city}}
</p>
<p>
  <button mat-raised-button (click)="openInfoDialog()">Info</button>
</p>

<ng-template let-data #myInfoDialog>
  <h2 mat-dialog-title>Information</h2>
  <div mat-dialog-content>
    {{data}}
  </div>
  <div mat-dialog-actions>
    <button mat-button mat-dialog-close>Close</button>
  </div>
</ng-template> 
example-dialog.component.ts
import { Component, TemplateRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { UserDialogComponent } from './user-dialog.component';
import { User } from './user';

@Component({
  selector: 'example-dialog',
  templateUrl: './example-dialog.component.html',
})
export class ExampleDialogComponent {
  user = { name: '', city: '' };
  dialogRef: any;

  constructor(public dialog: MatDialog) { }

  // Opening Dialog created by Component
  openUserDialog() {
    this.dialogRef = this.dialog.open(UserDialogComponent, 
      { data: this.user, height: '350px', width: '250px', autoFocus: true });

    this.dialogRef.afterClosed().subscribe((result: User) => {
      console.log('The User dialog was closed.');
      console.log(result?.name + ' - ' + result?.city);
    });
  }
  
  // Opening Dialog created by ng-template
  @ViewChild('myInfoDialog') infoDialog = {} as TemplateRef<string>;  
  myInfo = "Namaste to the world!";
  openInfoDialog() {
    this.dialogRef = this.dialog.open(this.infoDialog, { data: this.myInfo });

    this.dialogRef.afterClosed().subscribe(() => {
      console.log('The Info dialog was closed.');
    });
  }  
} 
user.ts
export interface User {
    name: string;
    city: string;
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<example-dialog></example-dialog>`
})
export class AppComponent {
} 
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatDialogModule, MAT_DIALOG_DEFAULT_OPTIONS } from '@angular/material/dialog';

import { AppComponent } from './app.component';
import { ExampleDialogComponent } from './example-dialog.component';
import { UserDialogComponent } from './user-dialog.component';

@NgModule({
  declarations: [
    AppComponent,
    ExampleDialogComponent,
    UserDialogComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatButtonModule,
    MatInputModule,
    MatDialogModule
  ],
  providers: [
    {provide: MAT_DIALOG_DEFAULT_OPTIONS,
       useValue: { height: '200px', width: '250px', autoFocus: true }}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { } 

7. Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Dialog Example

8. Reference

Angular Material Dialog

9. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI











©2022 concretepage.com | Privacy Policy | Contact Us