© Venkata Keerti Kotaru 2020
V. K. KotaruAngular for Material Designhttps://doi.org/10.1007/978-1-4842-5434-9_15

15. Material Design: Alerts and Dialogs

Venkata Keerti Kotaru1 
(1)
Hyderabad, India
 

Alerts and dialogs have been integral to UI applications. They show messages and information that need the user’s attention in UI pop-overs. Most of these UI paradigms are a layer on top of the original interface. Although it is needed for prompting and conveying significant content and messages, do not show multiple alerts or pop-overs at once. Overusing alerts and dialogs can lead to a bad user experience.

The dialogs and alerts described in this chapter follow Material Design specifications. We begin by introducing Material dialog. This chapter provides getting-started instructions, usage in the sample application, and various configurations.

This chapter introduces the bottom sheet. This control is typically used for showing menus, options, and prompts. Integrating bottom sheets with the Angular application and the consistent approach followed while integrating additional Angular Material components are explained.

Finally, this chapter discusses using a snack bar for showing alerts and messages.

Material Dialog

Angular Material provides a dialog implementation that confines to Material Design principles. It provides the same look and feel and animations when opening and closing the dialog . The Material dialog’s components and directives are ready-made and easy to use.

A dialog can have detailed text and images. The UI paradigm supports elaborate content and multiple actions. In Figure 15-1, the user agreement is shown in a Material dialog. It allows the user to either agree or cancel.
../images/475625_1_En_15_Chapter/475625_1_En_15_Fig1_HTML.jpg
Figure 15-1

Sample Material dialog component

Getting Started

To use Angular Material’s model dialog, import the module containing the components and directives. In Listing 15-1, all the Material Design components are encompassed in superheroes-material-design.module.ts.

Import the MatDialogModule from the Angular Material repository. Import it into the NgModule (Angular module) encompassing all the Material Design code in the sample application.
import { MatDialogModule } from '@angular/material/dialog';
@NgModule({
  declarations: [
        // Removed code for brevity
  ],
  imports: [
    MatDialogModule,
  ],
  exports: [
        // Removed code for brevity
  ],
  entryComponents: []
})
export class SuperheroesMaterialDesignModule { }
Listing 15-1

Import Angular Material Dialog Module

Sample: Confirm Cancel

In the sample application, consider a scenario in which we show a confirmation message when creating a new superhero. We do so with a Material dialog. Let’s edit the Create Superhero Component to use the model dialog for the confirmation message.

We encapsulate code for the Material Dialog in a new component. Use an Angular CLI command to create a new component. Listing 15-2 creates the component in the superheroes-material-design module. The component is named CancelConfirmDialogComponent.
ng g component superheroes-material-design/cancel-confirm-dialog
Listing 15-2

Create a Component for Creating the Model Dialog

The newly created component needs to be added as an entry component in the SuperheroMaterialDesignModule. It is required for the Angular compiler. Consider Listing 15-3. Update the entryComponents array to include CancelConfirmDialogComponent. Lines 1 and 5 are added by the Angular CLI. See line 13, where we update the component as an entry component in the module.
1. // imports
import { MatDialogModule } from '@angular/material/dialog';
import { CancelConfirmDialogComponent } from './cancel-confirm-dialog/cancel-confirm-dialog.component';
2. @NgModule({
3.  declarations: [
4.    // Removed code for brevity
5.      CancelConfirmDialogComponent
6.  ],
7.  imports: [
8.    MatDialogModule,
9.  ],
10.  exports: [
11.    // Removed code for brevity
12.  ],
13.  entryComponents: [CancelConfirmDialogComponent]
14. })
15. export class SuperheroesMaterialDesignModule { }
Listing 15-3

Declare Cancel Confirm Dialog in the Angular Module

We use the following directives to create a Material dialog. Listing 15-3 builds a Material dialog. It is the HTML template for the component. Figure 15-2 shows the result.
  • mat-dialog-title: Title for the dialog. Always shows even if the content or body of the dialog scrolls. See lines 1, 2, and 3 in Listing 15-3.

  • mat-dialog-content: Workspace or the main content of the dialog. Shows a scrollbar when content exceeds predefined height of the dialog. See lines 4, 5, and 6 in Listing 15-3.

  • mat-dialog-actions: Footer section of the dialog. Always shows, like the title. Typically, encompasses action buttons like Confirm, Cancel, and so forth. See lines 7 to 10 in Listing 15-3.

  • mat-dialog-close: The directive works on actions or buttons. It closes the dialog on click. In Listing 15-4, see lines 8 and 9. Notice the JSON specified. The field names and values in it are arbitrary.

    It returns the JSON result to the parent component. In the sample, we identify the button clicked by providing the title of the OK or Cancel button. The parent component receives this JSON and makes the appropriate decision.

1. <h1 mat-dialog-title>
2.  Are you sure?
3. </h1>
4. <div mat-dialog-content>
5.  Are you sure to cancel without saving the data?
6. </div>
7. <div mat-dialog-actions>
8.   <button mat-button [mat-dialog-close]="{clicked:'Ok'}">Ok</button>
9.   <button mat-button [mat-dialog-close]="{clicked:'Cancel'}">Cancel</button>
10. </div>
Listing 15-4

Model Dialog HTML Template

Figure 15-2 shows the result.
../images/475625_1_En_15_Chapter/475625_1_En_15_Fig2_HTML.jpg
Figure 15-2

Material Dialog on cancel in Create Superhero

Launch Material Dialog

So far, we have created a dialog that shows on click of the Cancel button. Next, we will launch the component in Listing 15-4 from the Create Superhero component. It is the parent component for the Material dialog. Remember, the Create Superhero component has an elaborate form to accept superhero information. If the user chooses to abort creating a superhero, she may click the Cancel button. The application shows a dialog to confirm the cancel action.

We use the MatDialog service to launch the dialog. Import and inject the service to CreateSuperheroComponent. In Listing 15-5, note the constructor in line 3, which injects the service.
1. // Imports
   import { MatDialog, MatDialogRef } from '@angular/material/dialog';
   import { CancelConfirmDialogComponent } from '../cancel-confirm-dialog/cancel-confirm-dialog.component';
2. // Removed code for brevity
3. export class CreateSuperheroComponent implements OnInit {
4.  constructor(private dialog: MatDialog) {
5.  }
6.  cancelHeroCreation() {
7.    const ref: MatDialogRef<CancelConfirmDialogComponent> = this.dialog.open(CancelConfirmDialogComponent);
8.    ref.afterClosed().subscribe( (data) => {
9.      if(data.clicked === "Ok"){
10.        // Reset form here
11.      } else if(data.clicked === "Cancel"){
12.        // Do nothing. Cancel any events that navigate away from the component.
13.      }
14.    });
15.  }
16.}
Listing 15-5

Launch Material Dialog

The cancel action invokes a cancelHeroCreation() function, which is defined in line 6. Next, to launch the dialog component created in Listing 15-5, we call the open() function on the service instance (this.dialog). Use the open() function with an input parameter and the dialog component class reference, which is imported in line 1.

In line 7, the open function returns a reference of the dialog component. It is assigned to a variable ref of type ModelDialogRef. It also uses a generic type to which we specify the component name created in Listing 15-5.

We have launched the model dialog. Next, we need to code the logic that acts on user choice. She may confirm aborting a superhero creation or continue with the create form. In either case, as the user chooses, the Model Dialog closes.

To do this, we call afterClosed(), which returns an observable. Subscribe to it (see lines 8 to 14). The success callback is invoked as the user finishes with the model dialog. The user can click the OK button or the Cancel button. Depending on the selection, the parent component makes a decision to reset the form or do nothing.

The JSON object returned from the Material dialog in Listing 15-5 (lines 8 and 9) is received on the success handler of subscribe in the parent component (see line 8 in Listing 15-5).

Send Data to the Material Dialog

We can provide additional parameters when opening the Material dialog. Data is one of the pieces of information that the parent component can provide to the Material dialog. In Listing 15-6, the parent component provides a message to be shown in the Material dialog. See lines 3 to 5.
--- create-superhero.component.ts ---
1.    let ref: MatDialogRef<CancelConfirmDialogComponent>
2.        = this.dialog.open(CancelConfirmDialogComponent, {
3.          data: {
4.            message: "Create Superhero action attempted to be cancelled"
5.          }
6.        });
Listing 15-6

Provide Data to the Material Dialog

To access the data, the object is injected into the constructor of the model dialog component. Use the MAT_DIALOG_DATA token to identify the dialog data. Consider Listing 15-7.
--- cancel-confirm-dialog.component.ts ---
1. import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
2. @Component({
3.     // Removed code for brevity
4. })
5. export class CancelConfirmDialogComponent implements OnInit {
6.  message: string;
7.  constructor(public dialogRef: MatDialogRef<CancelConfirmDialogComponent>,
8.    @Inject(MAT_DIALOG_DATA) data: { message: string}) {
9.      this.message = data.message;
10.  }
11. }
Listing 15-7

Access Data Provided by the Parent

Note In line 8, we are using an anonymous type for simplicity. We can use a predefined class instead.

The data object and the message field are the data provided by the parent component in line 9. We set the message in the class property, which is used in the HTML template. It shows the message in the dialog.

We can set the following parameters (or configurations) when launching a dialog. Listing 15-8 is a sample that sets the height, width, and backdrop, in addition to providing text (or data). Figure 15-3 shows the result. Compare it to Figure 15-2, to which we did not provide any configuration.
  • id: Overrides the default auto-generated ID for the dialog

  • width: A predefined width for the dialog, including units, pixels (px), points (pt), and so forth.

  • minWidth: A predefined minimum width for the dialog, including units , pixels (px), points (pt), and so forth. The dialog grows if the content does not fit in the provided width. It would at least be set at this width, even if the content is smaller.

  • height: A predefined height for the dialog, including units, pixels (px), points (pt), and so forth.

  • minHeight: A predefined minimum height for the dialog, including, pixels (px), points (pt), and so forth. The dialog grows if the content does not fit in the provided height. It would at least be set at this width, even if the content is smaller.

  • panelClass: A CSS class for the panel. Overrides the default.

  • position: Set a value—top, bottom, left, or right—for the dialog position.

  • autoFocus: Automatically focuses on the first element in the dialog.

  • disableClose: If true, the dialog will not close on keyboard escape or from clicking outside the dialog area.

  • hasBackdrop: If false, the dialog does not add a layer dimming the backdrop parent component.

    let ref: MatDialogRef<CancelConfirmDialogComponent>
        = this.dialog.open(CancelConfirmDialogComponent, {
          width: "800px",
          height: "200px",
          data: {
            message: "Create Superhero action attempted to be cancelled"
          },
          hasBackdrop: true
        });
Listing 15-8

Launch Material Dialog with a Configuration

The results are shown in Figure 15-3.
../images/475625_1_En_15_Chapter/475625_1_En_15_Fig3_HTML.jpg
Figure 15-3

Material dialog launched with a configuration, by the parent component

Provide Default Configuration for Material Dialog

We can provide a default configuration at the module level. It is used by all instances of the Material dialog. It is useful if we do not wish to customize each instance of a model dialog. Rather, use the parameters (or configuration) throughout the entire module. It helps provide consistency in the look and feel and behavior.

Listing 15-9 uses the MAT_DIALOG_DEFAULT_OPTIONS provider key. It is of type InjectionToken<MatDialogConfig<any>>. This configuration for the Material dialog is supplied by module-level providers. Hence, it is applied on all relevant components of the module
import { MatDialogModule, MAT_DIALOG_DEFAULT_OPTIONS } from '@angular/material/dialog';
@NgModule({
  declarations: [
        // Removed code for brevity
  ],
  imports: [
        // Removed code for brevity
  ],
  exports: [
        // Removed code for brevity
  ],
  providers:[
    {
      provide: MAT_DIALOG_DEFAULT_OPTIONS,
      useValue: {
        minWidth: "1020px",
        minHeight: "800px",
        hasBackdrop: true,
        disableClose:false
      }
    }
  ],
  entryComponents: [CancelConfirmDialogComponent]
})
export class SuperheroesMaterialDesignModule { }
Listing 15-9

Material Dialog Default Configuration

Send Data to the Parent Component

Consider the Material dialog that we created earlier. The two lines of code in Listing 15-10 show the Confirm and Cancel buttons.
<button mat-button [mat-dialog-close]="{clicked:'Ok'}">Ok</button>
<button mat-button [mat-dialog-close]="{clicked:'Cancel'}">Cancel</button>
Listing 15-10

(Partial Snippet from Listing 15-9) OK and Cancel Buttons in Material Dialog

We sent data to the parent component using the mat-dialog-close directive. The data identified the button selected by the user in the Material dialog. Based on the selection, the parent component decides to either clear the form or do nothing.

Alternatively, we may use a Material dialog reference to communicate from the dialog component to the parent component. Consider Figure 15-4. We briefly mentioned the use case at the beginning of the chapter. Imagine that the user agreement dialog is launched from the toolbar. In Figure 15-4, the Material dialog component shows the content of the user agreement. As the user types his name in the text field and submits the form, the toolbar receives the data. Figure 15-4 shows the name of the user.

To access the dialog reference, inject the ModelDialogRef service into the Material dialog component (the component that shows the user agreement). See Listing 15-10. We did the same in Listing 15-11 for CancelConfirmDialog.
export class SoftwareAgreementComponent implements OnInit {
   constructor(public dialogRef: MatDialogRef<SoftwareAgreementComponent>) {
  }
}
Listing 15-11

Inject Material Dialog Reference

../images/475625_1_En_15_Chapter/475625_1_En_15_Fig4_HTML.jpg
Figure 15-4

Pass data from Material dialog to parent component

Consider the function on clicking the Agree button in Listing 15-12. We use a dialog reference variable and close the model dialog. Pass the two fields of information: the title of the selected button (agree/cancel) and the full name entered by the user.
  onAgree(){
    this.dialogRef.close({
      clicked: "agree",
      fullName: this.fullName
    });
  }
Listing 15-12

Close the Dialog and Send Data to Parent Component

This accomplishes functionality similar to that of mat-dialog-close. However, mat-dialog-close is a directive used in the HTML template. It closes the model dialog. It provides limited but commonly used, ready-made functionality.

MatDialogRef provides finer control. We may choose to conditionally close the dialog, perform additional actions, and so on. We may send elaborate content or JSON objects back to the parent component, which is difficult to achieve with a directive in the HTML template.

The parent component accesses the dialog state as before. Listing 15-12 (the user agreement example) is similar to Listing 15-13’s lines 8 to 13. We show the name field accessed from the model dialog on the component.
      dialogRef.afterClosed()
      .subscribe(
        (data) => this.fullName = data.fullName
      );
Listing 15-13

Access Data Obtained from the Dialog

Bottom Sheet

Bottom sheet provides supplementary content and alerts. We may use it to show a list of the available options, menu items, and so forth.

As the name suggests, it is positioned at the bottom of the page. Consider an example in the context of Superheroes application. For a selected record, a list of available actions can be shown in a bottom sheet. Figure 15-5 shows options to share, print, message, or delete a selected superhero.

Similar to Material dialog, a bottom sheet supports selecting from multiple available actions. It may not use as much screen space as that of a dialog. The UI paradigm is useful for targeted actions that do not need to showcase elaborate information.
../images/475625_1_En_15_Chapter/475625_1_En_15_Fig5_HTML.jpg
Figure 15-5

Material Design bottom sheet

Getting Started

To use Angular Material’s bottom sheet, import MatBottomSheetModule, which contains the components and directives. In Listing 15-14, all the Material Design components are encompassed in superheroes-material-design.module.ts.

Import MatBottomSheetModule from the Angular Material repository into the NgModule (Angular module) encompassing all the Material Design code in the sample application.
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
@NgModule({
  declarations: [
        // Removed code for brevity
  ],
  imports: [
    MatBottomSheetModule,
  ],
  exports: [
        // Removed code for brevity
  ],
  entryComponents: []
})
export class SuperheroesMaterialDesignModule { }
Listing 15-14

Import Angular Material Bottom Sheet Module

Let’s continue with the use case discussed with the Material dialog. On aborting to create a new superhero, we show a confirmation message (on click of the Cancel button). We may do so with a bottom sheet (instead of a Material dialog). Let’s edit Create Superhero Component to use the bottom sheet for the confirmation message (see Figure 15-6).
../images/475625_1_En_15_Chapter/475625_1_En_15_Fig6_HTML.jpg
Figure 15-6

Cancel confirmation with bottom sheet

We encapsulate the code for the bottom sheet in a new component. Use the Angular CLI command to create a new component. Listing 15-15 creates the component in the superheroes-material-design module. The component is named CancelConfirmBottomSheetComponent.
ng g component superheroes-material-design/cancel-confirm-bottomsheet
Listing 15-15

Create a Component for Creating the Model Dialog

Like Material dialog, the bottom sheet needs to be registered as an entry component in the superhero-material-design module. This is required for the Angular compiler. Listing 15-16 line 1 imports the newly created component. Line 12 adds the component to the entry components array in the Angular module.
1. import { CancelConfirmBottomSheetComponent } from './cancel-confirm-bottomsheet/cancel-confirm-bottomsheet.component';
2. @NgModule({
3.  declarations: [
4.    // Removed code for brevity
5.  ],
6.  imports: [
7.    MatBottomSheetModule,
8.  ],
9.  exports: [
10.   // Removed code for brevity
11.  ],
12.  entryComponents: [CancelConfirmBottomSheetComponent]
13.})
export class SuperheroesMaterialDesignModule { }
Listing 15-16

Import Angular Material Dialog Module

Next, edit the HTML template of the newly created bottom sheet component. We show the confirmation message here (see Listing 15-17).
1. <div>
2.  <h2>
3.    Are you sure?
4.  </h2>
5.  <div>
6.    Are you sure to cancel without saving the data?
7.    {{ message }}
8.  </div>
9.  <mat-divider></mat-divider>
10.  <div>
11.    <button mat-button (click)="onOkClick()">Ok</button>
12.    <button mat-button (click)="onCancelClick()">Cancel</button>
13.  </div>
14. </div>
Listing 15-17

Form Cancel Confirmation Message in Bottom Sheet

Note The mat-divider component is in line 9. It is a horizontal ruler or a separator between the message and the action buttons.

The click events data binding with TypeScript component functions is shown in lines 11 and 12 (onOkClick() and onCancelClick()). Consider code for the same in Listing 15-17. The bottom sheet component communicates with the parent component and passes the state of the bottom sheet. It passes the information whether the user clicked the OK button or the Cancel button. See the complete code in Listing 15-18.
1. import { MatBottomSheetRef } from '@angular/material/bottom-sheet';
2. @Component({
3.  // removed code snippet for brevity
4. })
5. export class CancelConfirmBottomSheetComponent implements OnInit {
6.  constructor(private bottomSheetRef: MatBottomSheetRef) { }
7.  ngOnInit() {
8. }
9.  onOkClick(){
10.    this.bottomSheetRef.dismiss({ clicked: "Ok"});
11.  }
12.  onCancelClick(){
13.    this.bottomSheetRef.dismiss({ clicked: "Cancel"});
14.  }
15.}
Listing 15-18

Bottom Sheet TypeScript File Component

In the constructor in line 6, we inject the MatBottomSheetRef variable, referencing the bottom sheet. We use this reference variable to dismiss the bottom sheet in the click event handler function and cancel the event handler function.

When we create and show the bottom sheet (in the parent component), the reference is also returned to the parent component. The parent component can subscribe to observables in BottomSheetRef. The subscription helps receive data from the child component (the bottom sheet is the child component) and perform actions like “close”. This time, the close action can be performed from the parent component.

In lines 10 and 13, the dismiss API accepts the JSON object as an input parameter. In this sample, we pass the information, whether or not the OK or Cancel buttons have been clicked.

In Listing 15-19, the parent component subscribes to the observable that receives data from the bottom sheet. The observable is returned by the afterDismissed() function, which streams an event only after dismissing the bottom sheet (see line 3).
1.  cancelCreate(){
2.      let ref = this.bottomSheet.open(CancelConfirmBottomSheetComponent);
3.      ref.afterDismissed().subscribe( data => {
4.        if(data.clicked === "Ok"){
5.          // Reset form here
6.        }else if(data.clicked === "Cancel"){
7.        // Do nothing. Cancel any events that navigate away from the component.
8.       }
9.     });
10. )
Listing 15-19

Parent Component Subscribes to Observable from Bottom Sheet

Send Data to the Bottom Sheet

We can provide additional parameters (or configuration) when opening the bottom sheet. Data is one of the pieces of information that the parent component can provide to the bottom sheet. Listing 15-20 provides a message to be shown in the Material dialog (see lines 3 to 5).
1.      let ref = this.bottomSheet.open(CancelConfirmBottomSheetComponent,
2.        {
3.          data: {
4.          message: "Create Superhero action attempted to be cancelled"
5.        }
6.      });
Listing 15-20

Provide Data to the Bottom Sheet

To access the data, the object is injected into the constructor of the cancel confirmation bottom sheet component. Use the MAT_BOTTOM_SHEET_DATA token to identify the bottom sheet data (see Listing 15-21).
1. import { MatBottomSheetRef, MAT_BOTTOM_SHEET_DATA } from '@angular/material/bottom-sheet';
2. export class CancelConfirmBottomSheetComponent implements OnInit {
3.  message: string;
4.  constructor(private bottomSheetRef: MatBottomSheetRef,
5.      @Inject(MAT_BOTTOM_SHEET_DATA) bottomsheetData:{ message:string}) {
6.        this.message = bottomsheetData.message;
7. }
Listing 15-21

Access Data Provided by the Parent

Note In line 5, we are using an anonymous type for simplicity. We can use a predefined class instead.

The bottomsheetData object and the message field are the values provided by the parent component. In line 6, we set a message on the class variable, which is used in the HTML template. It shows the message on the bottom sheet. Consider Listing 15-22.
 <div>
    Are you sure to cancel without saving the data?
    <div *ngIf="message">
      <strong>{{message}}</strong>
    </div>
 </div>
Listing 15-22

HTML Template Shows the Message, if Available

The following are additional configurations that we can set on the bottom sheet.
  • panelClass: A CSS class for the panel. Overrides the default.

  • autoFocus: Automatically focuses on the first element in the bottom sheet.

  • disableClose: If true, will not close the bottom sheet on keyboard escape or by clicking outside the bottom sheet area.

  • hasBackdrop: If false, the bottom sheet does not add a layer dimming the backdrop parent component.

Provide Default Configuration for Bottom Sheet

We can provide default configuration at the module level. It is used by all instances of the bottom sheet. It helps provide consistency in the look and feel and behavior.

Listing 15-23 uses the MAT_BOTTOM_SHEET_DEFAULT_OPTIONS provider key. It is of type InjectionToken<MatBottomSheetConfig<any>>.
import { MatBottomSheetModule, MAT_BOTTOM_SHEET_DEFAULT_OPTIONS } from '@angular/material/bottom-sheet';
@NgModule({
  declarations: [
        // Removed code for brevity
  ],
  imports: [
      MatBottomSheetModule,
        // Removed code for brevity
  ],
  exports: [
        // Removed code for brevity
  ],
  providers:[
    {
      provide: MAT_BOTTOM_SHEET_DEFAULT_OPTIONS,
      useValue: {
        hasBackdrop: false,
        disableClose: true
      }
    }
  ],
  entryComponents: [CancelConfirmBottomSheetComponent]
})
export class SuperheroesMaterialDesignModule { }
Listing 15-23

Bottom Sheet Default Configuration

Snack-bar

The snack-bar is useful for showing alerts and messages. The messages do not interrupt the user. Based on the configuration, fewer import messages are dismissed automatically after a stipulated number of milliseconds. This helps the user to not become distracted by all the messages and notifications.

A typical snack-bar message is shown at the bottom center of the page. However, it can be repositioned to display in any corner of the page. A snack-bar may have an action to discuss the alert. Alternatively, it may not have any action, and it is dismissed automatically after a few seconds.
../images/475625_1_En_15_Chapter/475625_1_En_15_Fig7_HTML.jpg
Figure 15-7

Material Design snack-bar

Getting Started

To use Angular Material’s snack-bar, import MatSnackBarModule, which contains the components and directives. In Listing 15-24, all the Material Design components are encompassed in superheroes-material-design.module.ts.

Import MatSnackBarModule from the Angular Material repository into the NgModule (Angular module) encompassing all Material Design code in the sample application.
import { MatSnackBarModule } from '@angular/material/snack-bar';
@NgModule({
  declarations: [
        // Removed code for brevity
  ],
  imports: [
    MatSnackBarModule,
  ],
  exports: [
        // Removed code for brevity
  ],
  entryComponents: []
})
export class SuperheroesMaterialDesignModule { }
Listing 15-24

Import Angular Material Snack-bar Module

To demonstrate showing an alert with snack-bar, imagine that an error occurred when deleting a record. For the simplicity of the code sample, we show the snack-bar alert as the user clicks the Delete button in the Superhero Details screen.

Now that the required Angular module for the snack-bar has been imported, inject the MatSnackBar service to the Superhero Profile Component. We use this instance to show a snack-bar alert. Consider Listing 15-25.
1. import { MatSnackBar } from '@angular/material/snack-bar';
2. @Component({
3.  // Removed code for brevity
4. })
5. export class SuperheroProfileComponent implements OnInit, OnChanges {
6.  constructor(private matSnackBar: MatSnackBar) {
8.   }
9. }
Listing 15-25

Import and Inject MatSnackBar Service to the Component

Make use of the snack-bar service injected to show the alert as needed. Listing 15-26 shows an error message. The first parameter of the open() function is the message shown in the snack-bar. The second parameter is the title of the action button in the snack-bar. Figure 15-8 shows the results.
  showDeleteError(){ // invoked when delete action errors out.
    this.matSnackBar.open("Error attempting to delete", "Okay!");
  }
Listing 15-26

Show the Snack-bar Alert

../images/475625_1_En_15_Chapter/475625_1_En_15_Fig8_HTML.jpg
Figure 15-8

Snack-bar alert after delete action fails

The following are additional configurations that we can use when showing a snack-bar.
  • duration: Shows the snack-bar for a specified number of milliseconds. After the timeout, it automatically closes if a value is specified.

  • horizontalPosition: Position the snack-bar on the left, center, or right of the screen. Possible values are “start” or “left”, “center”, “end” or “right”.

  • verticalPosition: Position the snack-bar on the top or bottom.

  • panelClass: A list of CSS classes that can be applied in a snack-bar.

  • direction: Specify the direction of the content within the snack-bar” left to right or right to left. Use the values ltr or rtl.

Listing 15-27 shows the message in the top right; it automatically closes after five seconds. It is aligned to show content from right to left. Figure 15-9 shows the result.
    this.matSnackBar.open("I am positioned different", "Okay!", {
      duration: 5000,
      horizontalPosition: "right",
      verticalPosition: "top",
      direction: "rtl"
    });
Listing 15-27

Snack-bar Additional Configuration

../images/475625_1_En_15_Chapter/475625_1_En_15_Fig9_HTML.jpg
Figure 15-9

Snack-bar positioned top right and with additional configuration

Conclusion

The chapter explains the purpose and usage of dialogs, pop-overs, and alerts. We began by introducing Material dialog.

Next, we covered importing and using a bottom sheet. The chapter explained sharing information between components as the user selects from available options in the bottom sheet.

Finally, the chapter introduced using a snack-bar to show alerts, including snack-bar configurations and positioning on the page.

Exercise

Modify the dinosaur information screen to be a Material dialog component. Show the dinosaur name and the complete details on the dialog. Provide options to delete, edit, and share. Show these options on a bottom sheet. Show success and failure messages using a snack-bar.

References

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.64.132