Monday, January 29, 2024
HomeSoftware DevelopmentBe taught Angular 11 MatDialog Fundamentals

Be taught Angular 11 MatDialog Fundamentals


Developer.com content material and product suggestions are editorially impartial. We might earn a living while you click on on hyperlinks to our companions. Be taught Extra.

Of all of the Angular Materials elements, the MatDialog simply often is the most advanced. On the similar time, it’s most likely additionally essentially the most versatile of the bunch. A part of the reason being that it’s not a part a lot as a service that may be utilized to open modal dialogs with Materials Design styling and animations. On this tutorial, we’ll substitute the usual JavaScript verify dialog that we applied within the Stopping Information Loss In Angular Purposes utilizing a CanDeactivate Route Guard tutorial with a MatDialog:

JavaScript Verify Dialog

Angular Verify 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 are going to now add MatDialog to the listing:

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() technique accepts a part to point out within the physique of the dialog. You may be tempted to create the part as a toddler to the one that can name it, however it may be smart to suppose twice earlier than doing in order we might wish to reuse the identical dialog elsewhere inside out software sooner or later. For that cause, I’d advocate producing it inside the app listing:

ng g c confirm-dialog

Within the confirm-dialog.part.ts file, we’ll modify the constructor to just accept a reference to the dialog in addition to the information that we are going to cross 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.part.html',
  styleUrls: ['./confirm-dialog.component.css'],
  // this can 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 knowledge: any) 
  { }
}

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

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

Invoking the MatDialog Service

Again within the survey.part.ts file, we’re able to replace the canExit() technique to current our customized dialog as an alternative 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() technique. It’s accountable for displaying the dialog.
  3. Invoke the openUnsavedChangesDialog() technique from canExit().

Right here is the up to date supply code for the survey.part.ts file that reveals the related modifications:

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

// SatisfactionRatings enum

@Part({
  selector: "app-survey",
  templateUrl: "./survey.part.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',
      knowledge: { 
        dialogTitle: 'Unsaved Modifications', 
        dialogMessageLine1: 'You may have unsaved modifications.',
        dialogMessageLine2: 'Are you certain you wish to go away the web page?',
        yesButtonText: 'Depart this Web page',
        noButtonText: 'Keep on this Web page'
      }
    });

    return dialogRef.afterClosed();
  }
}

The openUnsavedChangesDialog() Methodology Defined

There’s rather a lot happening on this little technique, so let’s unpack it.

The dialog reference that we injected by way of the constructor gives quite a few strategies, properties, and occasion hooks for working with it, a very powerful of which being the open() technique. It accepts the part to show in addition to a MatDialogConfig object. That’s the place we set the dialog’s look and cross alongside the information object that populates the dialog part.

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 are able to do no matter processing we have to do after the dialog is closed. In our case, we don’t have to do something however cross alongside the worth returned by the dialog. That will get set by the 2 buttons within the footer by way of the certain [mat-dialog-close] attribute:

<div class="dialog-footer">
  <button class="standard-button dialog-button" mat-raised-button [mat-dialog-close]="false" cdkFocusInitial>{{knowledge.noButtonText}}</button>
  &nbsp;&nbsp;
  <button mat-raised-button shade="main" [mat-dialog-close]="true">{{knowledge.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 top results of right now’s updates to the Stopping Information Loss In Angular Purposes 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 Residence hyperlink:

Conclusion

On this tutorial, we discovered how one can use the MatDialog, essentially the most advanced, and but most versatile Angular Materials part. To do this, we changed the usual JavaScript verify dialog that we applied within the Stopping Information Loss In Angular Purposes utilizing a CanDeactivate Route Guard demo with a MatDialog.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments