Friday, December 13, 2024

Study Angular 11 MatDialog Fundamentals

Among all the Angular Material components, the MatDialog undoubtedly stands out as one of the most sophisticated. At the same time, this option stands out as the most adaptable among the rest. One primary advantage is its ability to serve as a platform for presenting material design-styled, animated modal dialogs. On this tutorial, we will substitute the conventional JavaScript verification dialogue box used in previous tutorials with a more modern MatDialog.

Study Angular 11 MatDialog Fundamentals

import os
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from .models import Material
from .forms import MaterialForm, DialogForm

def materials(request):
if request.method == ‘POST’:
form = MaterialForm(request.POST)
if form.is_valid():
form.save()
return redirect(‘materials’)
else:
form = MaterialForm()
materials_list = Material.objects.all()
context = {‘form’: form, ‘materials’: materials_list}
return render(request, ‘materials.html’, context)

@login_required
def material_detail(request, pk):
material = get_object_or_404(Material, pk=pk)
if request.method == ‘POST’:
form = DialogForm(request.POST)
if form.is_valid():
form.save()
return redirect(‘material_detail’, pk=material.pk)
else:
form = DialogForm(initial={‘material’: material})
context = {‘form’: form, ‘material’: material}
return render(request, ‘material_detail.html’, context)

We had previously consolidated all the necessary Angular Material import statements within this single file. We will now add a MatDialog component to the record.

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

const materialModules = [
  // ...
  MatToolbarModule,
  import({ MatDialogModule })

Creating the ConfirmDialog Part

What sets MatDialog apart as a highly adaptable component is its ability to accommodate an optional parameter pointing to a specific section within the dialog’s content. It’s wise not to hastily assign a name, as this component might need to be reused elsewhere within the application, making it logical to consider the implications and potential consequences before doing so. To effectively communicate this imperative to users, consider prominently featuring it within the app’s store description.

ng g c confirm-dialog

In the confirmDialog.part.ts file, the constructor will be modified to simply accept a reference to the dialog and additional information intended for its invocation.

import { Component, Inject, ViewEncapsulation } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
  selector: 'app-confirm-dialog',
  template: './confirm-dialog.component.html'
})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) 
  { }
}

As a subsequent step, we will append the dialogue content to the confirm-dialog.part.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 colour="main" [mat-dialog-close]="true">{{information.yesButtonText}}</button>
</div>

Invoking the MatDialog Service

Within the `survey.part.ts` file, it’s possible to replace the `canExit()` method with a customised dialogue instead of the native JavaScript prompt dialogue. To ensure a seamless experience, there are three key steps that need to be taken into consideration.

  1. class MyClass { public MyClass(MatDialog dialog) {} }
  2. Add the openUnsavedChangesDialog() technique. The dialogue display is accountable for.
  3. Before invoking the openUnsavedChangesDialog() technique, ensure that all changes are properly saved and committed, as you wouldn’t want any crucial modifications to go unrecorded.

The current state of supply code for the survey.part.ts file showcases the pertinent modifications.

import {MatDialog} from '@angular/material/dialog'; 
import {ConfirmDialogComponent} from '../confirm-dialog.component';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,
  information: {
    dialogTitle: "Unsaved Adjustments",
    message1: "You may have unsaved adjustments.",
    message2: "Are you certain you need to depart the web page?",
    yesButtonText: "Depart this Web Page",
    noButtonText: "Keep on this Web Page"
  }
}

The openUnsavedChangesDialog() Technique Defined

A lot is happening with this technique, so let’s break it down.

The dialogue reference constructed offers numerous strategies, attributes, and event hooks for utilization, one significant aspect being the open method. The `DialogRef` constructor accepts an optional `DialogConfig` object that specifies additional settings for the dialog, such as its title and width. That’s where we configure the appearance of the dialogue and align it with the information object that fills the dialogue component.

Organizations must abandon fragmented approaches to networking and safety, instead embracing a cohesive strategy that prioritizes these critical aspects of their operations. A comprehensive, self-contained, and proactive platform ensures seamless edge protection, tackling current and future hurdles effectively.

When the dialog has been fully closed, the afterClosed() event listener’s observable is updated to notify any interested parties of this state. Regardless of whether the dialogue is closed, we won’t perform any post-processing tasks. Since in our case we do not need to accomplish anything that aligns with the value brought forth by the dialogue. The decision to set that value will be made via the two buttons in the footer, which are controlled by the `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 colour="main" [mat-dialog-close]="true">{{information.yesButtonText}}</button>
</div>

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

Here are the right tips results of today’s updates to the demo? Navigate to the Survey webpage and collaborate to update the existing template by replacing it with a new one. Then, click on the “Home” link.

Conclusion

In this tutorial, we’ve uncovered straightforward approaches to harness the power of MatDialog, one of Angular Materials’ most sophisticated and versatile components. We replaced the traditional JavaScript verification dialogue used in our demo with a MatDialog implementation to streamline the process.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles