Angular Material 13 Display Snackbar Notification Tutorial

Angular Material 13 Snackbar notification example; In this comprehensive tutorial, we will show you how to create snackbar notification component in Angular app using Angular material’s snackbar user interface component from scratch.

Not only but we will also show you how to customize the snackbar component in Angular using material snackbar properties and options.

MatSnackBar is a convenient service that is offered by angular material, and it is a significant UI component that helps in displaying snack-bar notifications in Angular applications.

The Angular Snackbar component offers feedback about an ongoing operation with a single-line message that informs the user regarding an action.

The Snackbar message manifests above all other items and is generally positioned at the bottom center of the screen. However, you can change its positions based on the properties provided by the material library.

How to Build Snackbar Notification in Angular using Angular Material Library

  • Step 1: Build Angular App
  • Step 2: Add Angular Material Library
  • Step 3: Create Material Module File
  • Step 4: Create Snackbar Notification Component
  • Step 5: Snackbar with Configurable Position
  • Step 6: Start Development Server

Build Angular App

Before you start following this guide, ensure that you have configured Node, and Npm in your development machine.

You have to run the given command to install Angular CLI.

npm install -g @angular/cli

Execute following command to create a new angular demo application.

ng new ng-material-demo

Without further ado, enter into the app folder.

cd ng-material-demo

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, therefore, you need to update the compilerOptions and angularCompilerOptions in tsconfig.json file for disabling the strict mode:

{
   “strict”: false, 
   "noImplicitReturns": false 
   "strictTemplates": false
}

Add Angular Material Library

Run the suggested command to add the angular material library in your angular app:

ng add @angular/material

You have to answer some question to set up the material library in angular.

  1. Choose a prebuilt theme name or “custom” for a custom theme:

    You can choose from prebuilt material design themes or set up an extensible custom theme.

  2. Set up global Angular Material typography styles:

    Whether to apply the global typography styles to your application.

  3. Set up browser animations for Angular Material:

    Importing the BrowserAnimationsModule into your application enables Angular’s animation system. Declining this will disable most of Angular Material’s animations.

Angular material requires you to add styling CSS in src/styles.scss file:

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Create Material Module File

Make src/material.module.ts file, in this file we will import all the material modules. We will need only MatSnackBarModule but we are using all the material modules it will save your time if you need any other material module for your project.

import { NgModule } from '@angular/core';
import { A11yModule } from '@angular/cdk/a11y';
import { CdkAccordionModule } from '@angular/cdk/accordion';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PortalModule } from '@angular/cdk/portal';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { CdkStepperModule } from '@angular/cdk/stepper';
import { CdkTableModule } from '@angular/cdk/table';
import { CdkTreeModule } from '@angular/cdk/tree';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatDividerModule } from '@angular/material/divider';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule, MatRippleModule } from '@angular/material/core';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';
import { OverlayModule } from '@angular/cdk/overlay';

@NgModule({
  exports: [
    A11yModule,
    CdkAccordionModule,
    ClipboardModule,
    CdkStepperModule,
    CdkTableModule,
    CdkTreeModule,
    DragDropModule,
    MatAutocompleteModule,
    MatBadgeModule,
    MatBottomSheetModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatNativeDateModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatSortModule,
    MatTableModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
    MatTreeModule,
    OverlayModule,
    PortalModule,
    ScrollingModule,
  ],
})

export class MaterialModule {}

Open the app/app.module.ts file, in this file we have to import CUSTOM_ELEMENTS_SCHEMA, MaterialModule, FormsModule, and ReactiveFormsModule.

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MaterialModule } from '../material.module';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})

export class AppModule {}

Create Snackbar Notification Component

To show the snackbar, import the default MatSnackBar module from from ‘@angular/material/snack-bar’ library, inject the MatSnackBar in constructor method so that it invokes as soon as the component is ready.

Next, define the initSnackBar function, pass the message and action arguments as the arguments later access the open method to show the snackbar on button click.

Open the app.component.ts file and update the given code into the file.

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

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

export class AppComponent {
  constructor(public matSnackBar: MatSnackBar) {}
  initSnackBar(message: string, action: string) {
    this.matSnackBar.open(message, action, {
      duration: 3000,
    });
  }
}

Add the given code in the app.component.html file.

<button (click)="initSnackBar('Doctore Strange', 'action')" mat-button>
  Display Snack-bar
</button>

Snackbar with Configurable Position

Generically, the Snackbar appears at the bottom center of the screen, though we can adjust its position, thanks to the Angular material team.

In the following code example, we will show you how to vertically and horizontally change the snack bar notification positions.

Open and update code in app.component.html file.

<mat-form-field appearance="fill">
  <mat-label>Horizontal position</mat-label>
  <mat-select [(value)]="horizontalPosition">
    <mat-option value="start">Start</mat-option>
    <mat-option value="center">Center</mat-option>
    <mat-option value="end">End</mat-option>
    <mat-option value="left">Left</mat-option>
    <mat-option value="right">Right</mat-option>
  </mat-select>
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>Vertical position</mat-label>
  <mat-select [(value)]="verticalPosition">
    <mat-option value="top">Top</mat-option>
    <mat-option value="bottom">Bottom</mat-option>
  </mat-select>
</mat-form-field>

<button
  mat-stroked-button
  (click)="openSnackBar()"
  aria-label="Angular Snackbar Example"
>
  Movie Time
</button>

Head over to app.component.ts file and insert the given code into the file.

import { Component } from '@angular/core';
import {
  MatSnackBar,
  MatSnackBarHorizontalPosition,
  MatSnackBarVerticalPosition,
} from '@angular/material/snack-bar';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  horizontalPosition: MatSnackBarHorizontalPosition = 'start';
  verticalPosition: MatSnackBarVerticalPosition = 'bottom';

  constructor(private _snackBar: MatSnackBar) {}

  openSnackBar() {
    this._snackBar.open('Cannonball!!', 'Splash', {
      horizontalPosition: this.horizontalPosition,
      verticalPosition: this.verticalPosition,
    });
  }
}

Start Development Server

Execute the given command to run the angular application.

ng serve --open

The above command will open the app on the following url on the browser:

http://localhost:4200

Angular Material 13 Display Snackbar Notification Tutorial

Conclusion

Snackbar is a vital UI feature ideally used in front-end applications, and it is a small popup block that shows essential messages.

It provides an ideal way to get users’ attention by not hampering the user experience on the existing web page. The great thing about snackbar is that it disappears automatically after a certain period.

This chapter has taught us how to showcase the configuration required to display a snack bar notification using the Angular Material UI library.