web
mobile
Edit these docs Rate these docs

Angular Notification / Toast

Angular notification / toast - Bootstrap 4 & Material Design

Angular Bootstrap notifications are feedback messages that are displayed after specific actions enacted by the user. The text length is unlimited.

With the right use of colors, they add some emotional weight to our information, ranging from a simple warning to a critical system failure or from an operation success to other neutral information.

Additional resources: Have a look at our tutorial about Web Push alerts


Basic example MDB Pro component

Info message Warning message Success message Error message

        <!--Info message-->
        <a mdbBtn color="info" class="waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
        <!--Warning message-->
        <a mdbBtn color="warning" class="waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
        <!--Success message-->
        <a mdbBtn color="success" class="waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
        <!--Error message-->
        <a mdbBtn color="danger" class="waves-light" (click)="showError()" mdbWavesEffect>Error message</a>
      

        import { Component } from '@angular/core';
        import { ToastService } from 'ng-uikit-pro-standard';

        @Component({
        selector: 'toast-component-example',
        templateUrl: 'toast.component.html',
        })

        export class ToastComponent {

        constructor(private toastrService: ToastService) {}

        showSuccess() {
          this.toastrService.success('Info message');
        }

        showError() {
          this.toastrService.error('Warning message');
        }

        showInfo() {
          this.toastrService.info('Success message');
        }

        showWarning() {
          this.toastrService.warning('Error message');
        }

        }
      

Important update!

Since version 4.3.7, Toast Service has to be imported separately as a singleton to avoid circular dependencies.

Import Toast Service as a singleton:

app.module.ts

import { ToastModule } from 'ng-uikit-pro-standard';
...

imports: [
...
ToastModule.forRoot(),
...
],
              
app.component.ts

import {ToastService} from 'ng-uikit-pro-standard'
...
constructor(
...
private toast: ToastService
...
) { }

Sample usage:


ngOnInit() {
  setTimeout(
  () => this.toast.info("It works!")
  );
}
              

Change opacity MDB Pro component

In some cases, you may want to change the default opacity value for each individual alert. To do this, add the opacity parameter to the toast options.


        <!--Info message-->
        <a mdbBtn color="info" class="waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
        <!--Warning message-->
        <a mdbBtn color="warning" class="waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
        <!--Success message-->
        <a mdbBtn color="success" class="waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
        <!--Error message-->
        <a mdbBtn color="danger" class="waves-light" (click)="showError()" mdbWavesEffect>Error message</a>
      

        import { Component } from '@angular/core';
        import { ToastService } from 'ng-uikit-pro-standard';

        @Component({
        selector: 'toast-opacity',
        templateUrl: 'toast-opacity.component.html',
        })

        export class ToastOpacityComponent {

        constructor(private toastrService: ToastService) { }

        showSuccess() {
          const options = { opacity: 1 };
          this.toastrService.success('Hello world!', 'Toastr success!', options);
        }

        showError() {
          const options = { opacity: 0.8 };
          this.toastrService.error('Error message', 'Toastr error!', options);
        }

        showInfo() {
          const options = { opacity: 0.5 };
          this.toastrService.info('Info message', 'Toastr info!', options);
        }

        showWarning() {
          const options = { opacity: 0.2 };
          this.toastrService.warning('Warnig message', 'Toastr warning!', options);
        }

        }
      

Show alerts after server call MDB Pro component

If you are in contact with a server, it may be useful to display alerts to the user on whether the data has been successfully downloaded or not. The following example illustrates the basic use of alerts in a server contact.


        <div class="row">
          <div class="col-md-6 mx-auto my-5">
            <h3 class="text-center py-2">Users: </h3>
            <ul class="list-group" *ngFor="let user of usersArray">
              <li class="list-group-item">{{ user }}</li>
            </ul>
          </div>
        </div>
      

        import { Http } from '@angular/http';
        import { ToastService } from 'ng-uikit-pro-standard';
        import { Component, AfterViewInit } from '@angular/core';

        @Component({
        selector: 'server-alerts',
        templateUrl: './server-alerts.component.html',
        styleUrls: ['./server-alerts.component.scss'],
        })
        export class ServerAlertsComponent implements AfterViewInit {
        url: string = 'https://jsonplaceholder.typicode.com/users/';
        usersArray: Array<any> = [];

          constructor(private toastrService: ToastService, private http: Http) { }

          showSuccess(data: any) {
            this.toastrService.success('User: ' + '"' + data.name + '"' + ' successfully fetched');
          }

          showError(id: number) {
            this.toastrService.error("Error: User with ID: " + id + " doesn't exists");
          }

          connectionEnd(id: number) {
            this.toastrService.error('Connection ended after ' + id + ' calls');
          }

          getData(id: number) {
            return this.http.get(this.url + id);
          }

          ngAfterViewInit() {
          let i = 1;

          const getDataInterval = setInterval(() => {
          this.getData(i).subscribe((response: any) => {
          response = response.json();
          this.usersArray.push(response.name);
          this.showSuccess(response);
          i++;
          }, error => {
          if (i < 15) { this.showError(i); } else { clearInterval(getDataInterval); this.connectionEnd(i); } i++; });
            }, 2000); }
          }
          

Remove single alert MDB Pro component

You can use the clear() method to remove an active alert with a specific id.


          <button mdbBtn color="primary" (click)="removeSingleAlert()">Remove single alert</button>
        

          import { Component } from '@angular/core';
          import { ToastService } from 'ng-uikit-pro-standard';

          @Component({
          selector: 'toast-remove',
          templateUrl: 'toast-remove.component.html',
          })

          export class ToastRemoveComponent {
          alertId: number;

          constructor(private toastrService: ToastService) {}

          showSuccess() {
            const successAlert = this.toastrService.success('Info message');
            this.alertId = successAlert.toastId;
          }

          removeSingleAlert() {
            this.toastrService.clear(this.alertId);
          }
        

Remove all alerts MDB Pro component

You can use the clear() method without parameters to remove all active alerts.


          <button mdbBtn color="primary" (click)="removeAlerts()">Remove alerts</button>
          <a mdbBtn color="info" class="waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
          <!--Warning message-->
          <a mdbBtn color="warning" class="waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
          <!--Success message-->
          <a mdbBtn color="success" class="waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
          <!--Error message-->
          <a mdbBtn color="danger" class="waves-light" (click)="showError()" mdbWavesEffect>Error message</a>
        

          import { Component } from '@angular/core';
          import { ToastService } from 'ng-uikit-pro-standard';

          @Component({
          selector: 'toast-remove',
          templateUrl: 'toast-remove.component.html',
          })

          export class ToastRemoveComponent {

          constructor(private toastrService: ToastService) {}

          showSuccess() {
            const options = { toastClass: 'opacity' };
            this.toastrService.success('Success message description', 'Success message', options);
          }

          showError() {
            const options = { toastClass: 'opacity' };
            this.toastrService.error('Error message description', 'Error message', options);
          }

          showInfo() {
            const options = { toastClass: 'opacity' };
            this.toastrService.info('Info message description', 'Info message', options);
          }

          showWarning() {
            const options = { toastClass: 'opacity' };
            this.toastrService.warning('Warning message description', 'Warning message', options);
          }

          removeAlerts() {
            this.toastrService.clear();
          }
        
Edit these docs Rate these docs

Angular Notification / Toast - API

In this section you will find informations about required modules and available inputs, outputs, methods and events of toasts.


Modules used

In order to speed up your application, you can choose to import only the modules you actually need, instead of importing the entire MDB Angular library. Remember that importing the entire library, and immediately afterwards a specific module, is bad practice, and can cause application errors.

// For MDB Angular Pro
import { ToastModule, WavesModule } from 'ng-uikit-pro-standard'
// Angular Animations Module
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'

Services

ToastService

Type: ToastService


Options

There are global and individual alert options. All individual alert options are included in the global options.

Global options for alerts need to be set in ToastModule.forRoot({}) in imports: [] array located in app.module.ts file.

For example, global options that allows only 2 alerts to be visible at time should look like this: ToastModule.forRoot({maxOpened: 2})

Please note that if you want to use following options to add your custom class, you have to put this class in your global stylesheet (styles.scss) as well.

Global options
Name Type Default Description Example
autoDismiss boolean false Dismiss current alert when max number of opened alerts is reached { autoDismiss: true }
iconClasses string error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' Classes used on toast service methods iconClasses = { error: 'md-toast-error', info: 'md-toast-info', success: 'md-toast-success', warning: 'md-toast-warning' };
maxOpened number 0 Max alerts opened, alerts will be queued (0 means unlimited) { maxOpened: 5 }
newestOnTop boolean true Whether new alert should be placed on top { newestOnTop: false }
preventDuplicates boolean false Allow or block duplicate messages { preventDuplicates: true }
Individual options
Name Type Default Description Example
actionButton string - Show action button with specified title { actionButton: 'Action button' }
actionButtonClass string - Add provided class to the toast action button { actionButtonClass: 'text-red my-5' }
closeButton boolean false Show close buttons { closeButton: true }
enableHtml boolean false Allow html in message (UNSAFE) { enableHtml: true }
extendedTimeOut number 1000 Time for which alert display will be extended after user hover over toast (in miliseconds) { extendedTimeOut: 2000 }
messageClass string 'md-toast-message' Class applied to alert message element { messageClass: 'custom-message' }
positionClass string 'md-toast-top-right' Class applied to alert container, used to change alert positioning { positionClass: 'md-toast-bottom-right' }
progressBar boolean false Show progress bar { progressBar: true }
tapToDismiss boolean true Close alert on click { tapToDismiss: false }
timeOut number 5000 Time by which the alert will be active (in miliseconds) { timeOut: 3000 }
titleClass string 'md-toast-title' Class applied to alert title { titleClass: 'custom-title' }
toastClass string 'md-toast' Class applied to alert { toastClass: 'custom-toast' }
Usage examples

      showSuccess() {
        const options = { closeButton: true, actionButton: 'Action', tapToDismiss: false,  titleClass: 'yellow' };
        this.toastrService.success('Hello world!', 'Toastr success!', options);
      }
      showError() {
        const options = { enableHtml: false,  positionClass: 'md-toast-bottom-right' };
        this.toastrService.error('Error message', 'Toastr error!', options);
      }

      showInfo() {
        const options = { extendedTimeOut: 30000, messageClass: 'pink' };
        this.toastrService.info('Info message', 'Toastr info!', options);
      }

      showWarning() {
        const options = { progressBar: true,  timeOut: 3000,  toastClass: 'black'};
        this.toastrService.warning('Warnig message', 'Toastr warning!', options);
      }

  

Events

Name Type Description Example
onAction any The event is fired when action button is clicked alertInstance.onAction.subscribe(() => {})
onHidden any The event is fired when tap on the alert is detected alertInstance.onHidden.subscribe(() => {})
onShown any The event is fired when alert shows on screen alertInstance.onShown.subscribe(() => {})
onTap any The event is fired when tap on the alert is detected alertInstance.onTap.subscribe(() => {}))
Usage examples

        showSuccess() {
          const options = { closeButton: true, progressBar: true, actionButton: 'Action', tapToDismiss: true};
          const alertInstance = this.toastrService.success('Hello world!', 'Toastr success!', options);
          alertInstance.onAction.subscribe(() => {
            console.log('on action');
          });
          alertInstance.onTap.subscribe(() => {
            console.log('on tap');
          });
          alertInstance.onShown.subscribe(() => {
            console.log('on shown');
          });
          alertInstance.onHidden.subscribe(() => {
            console.log('on hidden');
          });
        }

    

Methods

To get access to alert methods inject ToastService to your component:

constructor(private toastrService: ToastService) {}

Name Description
clear(alertId) Removes single active alert with specified id
clear() Removes all active alerts
Edit these docs Rate these docs

Angular Notification / Toast - examples & customization


Individual config options MDB Pro component


        <!--Info message-->
        <a mdbBtn color="info" class="waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
        <!--Warning message-->
        <a mdbBtn color="warning" class="waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
        <!--Success message-->
        <a mdbBtn color="success" class="waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
        <!--Error message-->
        <a mdbBtn color="danger" class="waves-light" (click)="showError()" mdbWavesEffect>Error message</a>
      

        import { ToastService } from 'ng-uikit-pro-standard';
        import { Component } from '@angular/core';

        @Component({
          selector: 'individual-config',
          templateUrl: './individual-config.component.html',
          styleUrls: ['./individual-config.component.scss'],
        })
        export class IndividualConfigComponent {
          constructor(private toastrService: ToastService) { }

          showSuccess() {
            const options = { closeButton: true, actionButton: 'Action', tapToDismiss: false, titleClass: 'yellow' };
            this.toastrService.success('Hello world!', 'Toastr success!', options);
          }
          showError() {
            const options = { enableHtml: false, positionClass: 'md-toast-bottom-right' };
            this.toastrService.error('Error message', 'Toastr error!', options);
          }

          showInfo() {
            const options = { extendedTimeOut: 30000, messageClass: 'pink' };
            this.toastrService.info('Info message', 'Toastr info!', options);
          }

          showWarning() {
            const options = { progressBar: true, timeOut: 3000, toastClass: 'black' };
            this.toastrService.warning('Warnig message', 'Toastr warning!', options);
          }

        }
      

Toast events MDB Pro component


          <!--Success message-->
          <a mdbBtn color="success" class="waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
        

          import { ToastService } from 'ng-uikit-pro-standard';
          import { Component } from '@angular/core';
  
          @Component({
            selector: 'toast-events',
            templateUrl: './toast-events.component.html',
            styleUrls: ['./toast-events.component.scss'],
          })
          export class ToastEventsComponent {
            constructor(private toastrService: ToastService) { }
  
            showSuccess() {
                const options = { closeButton: true, progressBar: true, actionButton: 'Action', tapToDismiss: true };
                const alertInstance = this.toastrService.success('Hello world!', 'Toastr success!', options);
                alertInstance.onAction.subscribe(() => {
                  console.log('on action');
                });
                alertInstance.onTap.subscribe(() => {
                  console.log('on tap');
                });
                alertInstance.onShown.subscribe(() => {
                  console.log('on shown');
                });
                alertInstance.onHidden.subscribe(() => {
                  console.log('on hidden');
                });
              }
          }