-3.1 C
New York
Tuesday, December 24, 2024

Study Angular 11 MatDialog Fundamentals


Of all of the Angular Materials elements, the MatDialog simply would be the most complicated. On the identical time, it’s in all probability additionally probably the most versatile of the bunch. A part of the reason being that it’s not a element a lot as a service that may be utilized to open modal dialogs with Materials Design styling and animations. On this tutorial, we’ll exchange the usual JavaScript verify dialog that we carried out within the Stopping Knowledge Loss In Angular Functions utilizing a CanDeactivate Route Guard tutorial with a MatDialog:

JavaScript Affirm Dialog

Study Angular 11 MatDialog Fundamentals

Angular Affirm Dialog

Including MatDialog to the Materials Module File

Recall that we positioned all of our Angular Materials imports within the srcappsharedmodulesmaterialmaterial.module.ts file. We’ll now add MatDialog to the checklist:

import {MatDialogModule} from '@angular/materials/dialog';

const materialModules = [
  //...
  MatToolbarModule,
  MatDialogModule
];

Creating the ConfirmDialog Part

A part of what makes MatDialog so versatile is that its open() methodology accepts a element to point out within the physique of the dialog. You could be tempted to create the element as a baby to the one that may name it, but it surely could be smart to assume twice earlier than doing in order we could wish to reuse the identical dialog somewhere else inside out utility sooner or later. For that cause, I’d suggest producing it inside the app listing:

ng g c confirm-dialog

Within the confirm-dialog.element.ts file, we are going to modify the constructor to just accept a reference to the dialog in addition to the info that we are going to move to it:

import { Part, Inject, ViewEncapsulation } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/materials/dialog';

@Part({
  selector: 'app-confirm-dialog',
  templateUrl: './confirm-dialog.element.html',
  styleUrls: ['./confirm-dialog.component.css'],
  // it will permit us to override the mat-dialog-container CSS class
  encapsulation: ViewEncapsulation.None
})
export class ConfirmDialogComponent {

  constructor(
    public dialogRef: MatDialogRef<ConfirmDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public information: any) 
  { }
}

Subsequent, we’ll add the contents of the dialog to the confirm-dialog.element.html file:

<div class="dialog-header accent-background">
  <span class="dialog-header-title">{{information.dialogTitle}}</span>
</div>
<div class="dialog-content">
  <p>{{information.dialogMessageLine1}}<br/>
  {{information.dialogMessageLine2}}</p>
</div>
<div class="dialog-footer">
  <button class="standard-button dialog-button" mat-raised-button [mat-dialog-close]="false" cdkFocusInitial>{{information.noButtonText}}</button>
    
  <button mat-raised-button coloration="main" [mat-dialog-close]="true">{{information.yesButtonText}}</button>
</div>

Invoking the MatDialog Service

Again within the survey.element.ts file, we’re able to replace the canExit() methodology to current our customized dialog as a substitute of the native JavaScript verify dialog. There are three issues we have to do to make that occur:

  1. Add a constructor that accepts a MatDialog reference.
  2. Add the openUnsavedChangesDialog() methodology. It’s liable for displaying the dialog.
  3. Invoke the openUnsavedChangesDialog() methodology from canExit().

Right here is the up to date supply code for the survey.element.ts file that exhibits the related adjustments:

// imports
import { MatDialog } from "@angular/materials/dialog";
import { ConfirmDialogComponent } from "../confirm-dialog/confirm-dialog.element";

// SatisfactionRatings enum

@Part({
  selector: "app-survey",
  templateUrl: "./survey.element.html",
  styleUrls: ["./survey.component.css"]
})
export class SurveyComponent implements IDeactivateComponent {
  // declarations

  constructor(public dialog: MatDialog) { }

  //strategies...

  public canExit(): boolean | Observable<boolean> {
    return this.ngFormRef.soiled
      ? this.openUnsavedChangesDialog()
      : true;
  };

  personal openUnsavedChangesDialog(): Observable<boolean> {
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '26.5rem',
      information: { 
        dialogTitle: 'Unsaved Adjustments', 
        dialogMessageLine1: 'You have got unsaved adjustments.',
        dialogMessageLine2: 'Are you positive you wish to go away the web page?',
        yesButtonText: 'Go away this Web page',
        noButtonText: 'Keep on this Web page'
      }
    });

    return dialogRef.afterClosed();
  }
}

The openUnsavedChangesDialog() Technique Defined

There’s lots happening on this little methodology, so let’s unpack it.

The dialog reference that we injected through the constructor supplies quite a few strategies, properties, and occasion hooks for working with it, a very powerful of which being the open() methodology. It accepts the element to show in addition to a MatDialogConfig object. That’s the place we set the dialog’s look and move alongside the info object that populates the dialog element.

Organizations should transcend a piecemeal method to networking and safety. A broad, built-in, and automatic platform that secures all edges addresses challenges now and sooner or later.

The afterClosed() occasion hook receives an observable that’s notified when the dialog is completed closing. We will do no matter processing we have to do after the dialog is closed. In our case, we don’t must do something however move alongside the worth returned by the dialog. That will get set by the 2 buttons within the footer through the sure [mat-dialog-close] attribute:

<div class="dialog-footer">
  <button class="standard-button dialog-button" mat-raised-button [mat-dialog-close]="false" cdkFocusInitial>{{information.noButtonText}}</button>
  &nbsp;&nbsp;
  <button mat-raised-button coloration="main" [mat-dialog-close]="true">{{information.yesButtonText}}</button>
</div>

We then want so as to add the Observable<boolean> return sort to canExit() to accommodate the afterClosed() return worth.

Right here’s the tip results of right this moment’s updates to the Stopping Knowledge Loss In Angular Functions utilizing a CanDeactivate Route Guard demo. To check it, navigate to the Survey web page, work together with the shape in order to replace the underlying mannequin, after which click on the Dwelling hyperlink:

Conclusion

On this tutorial, we realized use the MatDialog, probably the most complicated, and but most versatile Angular Materials element. To try this, we changed the usual JavaScript verify dialog that we carried out within the Stopping Knowledge Loss In Angular Functions utilizing a CanDeactivate Route Guard demo with a MatDialog.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles