How to implement angular material snackbar | toast in Angular 12 ?

Angular material snackbar component can be used to display notification information for a short period of time using Angular material SnackBarModule. Angular material snackbar or Angular material toast useful for showing alert and notification messages.

We’ll be exploring how to implement Angular material toast | snackbar by customizing Angular material snackbar CSS style, message, toast color, and toast position. Keeping one snack code for the whole application using Angular material toast service is best the practice of code reusability.

Angular material snackbar
Angular material toast

Step 1 : Setup and configure Angular material snack project

Let first create an Angular material snack project, we need to install the angular material library. Let’s create and install the angular material library.

ng new snackMaterialApp
cd snackMaterialApp
ng add @angular/material

While running the 3rd command will ask you the select theme, material typography, and animation, press yes on all. To use the Angular material component, we have to import it into our app module. Let create a module and import all material components on it.

ng g m ng-material
ng g c ng-material/snackBar

We also need to create a component to demonstrate how to pass data to snackbar components and how to add material icons in Angular material toast.

Angular material grid example

Open src/app/ng-material/ng-material.module.ts and replace the existing code with the code shown below.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { SnackBarComponent } from './snack-bar/snack-bar.component';

@NgModule({
  declarations: [
    SnackBarComponent
  ],
  imports: [
    CommonModule,
    MatSnackBarModule,
    MatButtonModule,
    MatIconModule
  ],
  exports: [
    MatSnackBarModule,
    MatButtonModule,
    MatIconModule
  ]
})
export class NgMaterialModule { }

We are importing all the required modules in our custom material module file and keeping separate modules for Angular material will make the application easy to maintain. Now we need to import our material module in the src/app/app.module.ts file.

...
import { NgMaterialModule } from './ng-material/ng-material.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
     ...
    NgMaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

How to implment Angular material snackbar ?

In our first Angular material snackbar example, we are using the MatSnackBar object directly in our component. In the second example, we’ll create a toast service. We are displaying an angular material toast at different positions on the page, add an action button on the snackbar.

Angular material snack position

Let edit the app.component.html template to add a button to demonstrate Angular material snackbar position and action button.

<div class="container">
  <h2>Angular material snackbar</h2>
  <button mat-raised-button color="accent" (click)="showBasicSnack()">Show snackbar</button>
  <button mat-raised-button color="accent" (click)="snackPositionTopCenter()">Show snackbar center bottom</button>

  <button mat-raised-button color="primary" (click)="defaultSnackbar()">
    Default Snackbar position
  </button>
  <button mat-raised-button color="primary"
    (click)="showSnackbarAction()">
    Snackbar action
  </button>

  <button mat-raised-button color="primary" (click)="showSnackbarDuration()">
    Snackbar Duration
  </button>

  <button mat-raised-button color="primary" (click)="showSnackbarCssStyles()">
    Snackbar CSS Styles
  </button>

  <button mat-raised-button color="primary" (click)="passDataToSnackComponent()">
    Snack with icon with passing data to component
  </button>

  <button mat-raised-button color="primary" (click)="callSnackService()">
    Snackbar common service</button>

  <router-outlet></router-outlet>
</div>

We need to import and inject the MatSnackBar object and we can call the open method to open snackbar. Let edit the app.component.ts file.

import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { SnackBarComponent } from './ng-material/snack-bar/snack-bar.component';
import { SnackBarService } from './services/snack-bar.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(
    private snackBarService: SnackBarService,
    private matSnackBar: MatSnackBar) { }

  showBasicSnack() {
    this.matSnackBar.open("Update successful", "Okay");
  }

  snackPositionTopCenter() {
    this.matSnackBar.open("I am positioned top center", "Okay!", {
      duration: 5000,
      horizontalPosition: "center",
      verticalPosition: "top",
      // direction: "rtl"
    });
  }

  defaultSnackbar() {
    this.matSnackBar.open('Default snackbar postion !');
  }

  showSnackbarAction() {
    let snack = this.matSnackBar.open('Snackbar with action button', 'Ok');

    snack.onAction().subscribe(() => {
      alert("This will be called when snackbar Done button clicked");
    });

    snack.afterDismissed().subscribe(() => {
      alert("This will be shown after snackbar disappeared");
    });
  }

  showSnackbarDuration() {
    this.matSnackBar.open("Snack duration, we set to 5 milliseconds", 
    'Dismiss', { duration: 5000 });
  }
}

The snackBar object has an open method, we can pass configuration for our angular material toast by using the following attributes.

Attribute nameDescription
durationA number of milliseconds before the toast is dismissed.
panelClassAn array containing the list of CSS classes that can be applied in a toast.
horizontalPositionPosition the snackBar on pagescreen and it can have values of “start” or “left”, “center”, “end” or “right”.

How to apply Angular material snackbar color

We can apply CSS classes to our Angular material toast, by using the CSS custom class name we can apply the background color.

Angular material snackbar color

Let add CSS class name to our snackbar using panelClass, edit the app.component.ts file.

  showSnackbarCssStyles() {
    let snackBarColor = this.matSnackBar.open("Snackbar style to change background color", 'Close', {
      duration: 4000,
      panelClass: ["snack-style"]
    });
    snackBarColor.onAction().subscribe(() => {
      snackBarColor.dismiss();
    });
  }

We had to add one class called snack-style, now let add different background colors to the Angular material alert and edit the app.component.scss file.

::ng-deep .snack-style{
    background-color:rgb(72, 236, 39);
    color: rgb(82, 82, 82);
}

We have used ng-deep with custom class names to apply Angular material snackbar color.

How to apply add material icon to Angular snackbar component

In this example, we’ll demonstrate how to send data to snackbar component, we also added a material icon on Angular material toast. Edit the app.component.ts file to open our custom SnackBarComponent.

passDataToSnackComponent() {
    this.matSnackBar.openFromComponent(SnackBarComponent, {
      data: 'Hi from Edupala',
      duration: 12000,
      panelClass: ["snack-notification"],
      horizontalPosition: "center",
      verticalPosition: "top",
    });
  }

Edit the snack-bar.component.ts to retrieve data from the component.

import { Component, Inject, OnInit } from '@angular/core';
import { MatSnackBarRef, MAT_SNACK_BAR_DATA } from '@angular/material/snack-bar';

@Component({
  selector: 'app-snack-bar',
  templateUrl: './snack-bar.component.html',
  styleUrls: ['./snack-bar.component.scss']
})
export class SnackBarComponent {

  constructor(
    public sbRef: MatSnackBarRef<SnackBarComponent>,
    @Inject(MAT_SNACK_BAR_DATA) public data: any
  ) {}
}

Let edit the snack-bar.component.html to the material icon in an alert component.

<div>
    <mat-icon aria-hidden="false" aria-label="Example home icon">
       notifications
    </mat-icon>
    <p class="information">
        <strong>Notification</strong><br>
        {{ data }}
    </p>
</div>

Here is our screenshot of the material snackbar component.

Angular material snackbar icon

How to implment Angular material snackbar using service ?

In application, toast, snackbar can apply at different pages | components. Is a good practice to create a common service where we add all our common code. In our case, we will create a material toast service. Let add code in the snack-bar.service.ts

import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root'
})
export class SnackBarService {

  constructor(private matSnackBar: MatSnackBar) { }

  openSnackBar(message: string, action: string,
    hPosition?: any, vPosition? : any,
    className?: any ) {
    this.matSnackBar.open(message, action, {
      duration: 5000,
      horizontalPosition: hPosition ? hPosition : 'center',
      verticalPosition: vPosition ? vPosition : 'top',
      panelClass: className
      // direction: "rtl"
    });
  }
}

In the SnackBarService we can import and injected matSnackBar object, we have only one method called openSnackBar with a few parameters of non-optional and optional parameters.

We can pass our custom message, action, position, and CSS class to our reusable service. To call this service we need to inject this service into our corresponding component. Let inject our custom SnackBarService in the app.component.ts file.

import { Component } from '@angular/core';;
import { SnackBarService } from './services/snack-bar.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(
    private snackBarService: SnackBarService) { }

  ....
  callSnackService() {
    this.snackBarService.openSnackBar(
      'Common code to implement using service',
      'Okey', 'center', 'top', 'snack-style');
  }
}

Now we can call any number of our custom snackBar service in any component we want.

Conclusion
We have completed our Angular material snackbar or Angular material toast. I hope you got some idea of how to use the Angular material dialog component.

Related Articles

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top