Rate this docs

Angular Notification / Toast

Angular notification / toast - Bootstrap 4 & Material Design

Angular Bootstrap notifications are feedback messages which are displayed after specific actions preceded by the user. Length of the text is not limited.

With the right use of colors, they add some emotional weight to our information, ranging from a simple warning to critical system failure or from an operation success to a 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 class="btn btn-info waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
        <!--Warning message-->
        <a class="btn btn-warning waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
        <!--Success message-->
        <a class="btn btn-success waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
        <!--Error message-->
        <a class="btn btn-danger 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');
          }

        }
      

Modifying opacity with toastClass

In some cases, you may want to change the default opacity value for each individual alert. To do this, use the toastClass option to assign a class containing the opacity styles.



      <!--Info message-->
      <a class="btn btn-info waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
      <!--Warning message-->
      <a class="btn btn-warning waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
      <!--Success message-->
      <a class="btn btn-success waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
      <!--Error message-->
      <a class="btn btn-danger 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() {
            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);
          }

        }
      

        .opacity {
          opacity: 1.0 !important;
        }
      

Showing alerts after server call

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);
          }
        }
      

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'

Classes

GlobalConfig

Type: GlobalConfig

IndividualConfig

Type: IndividualConfig

ToastService

Type: ToastService


Options

GlobalConfig
Name Type Default Description Example
maxOpened number 0 Max toasts opened; toasts will be queued. ToastModule.forRoot({maxOpened: 2})
autoDismiss boolean false Dismiss current toast when max is reached. ToastModule.forRoot({autoDismiss: true})
newestOnTop boolean true New toast placement ToastModule.forRoot({newestOnTop: false})
preventDuplicates boolean false Block duplicate messages ToastModule.forRoot({preventDuplicates: true})
IndividualConfig
Name Type Default Description Example
actionButton string - Show action button with specified title. actionButton: true
closeButton boolean false Show close button. this.toastrService.success('Hello world!', 'Toastr success!', {closeButton: true});
timeOut number 5000 Time to live - in ms. this.toastrService.success('Hello world!', 'Toastr success!', {timeOut: 1000});
enableHtml boolean false Allow to inject HTML code in message - potentially unsafe. this.toastrService.success('Hello world!', 'Toastr success!', {enableHtml: true});
extendedTimeOut number 1000 Time to close after a user hovers over toast. this.toastrService.success('Hello world!', 'Toastr success!', {extendedTimeOut: 500});
progressBar boolean false Show progress bar. this.toastrService.success('Hello world!', 'Toastr success!', {progressBar: true});
toastClass string 'toast' Class on toast. Note that if you want to add your custom class, you have to put it in your's global stylesheet - styles.scss. this.toastrService.success('Hello world!', 'Toastr success!', {toastClass: 'custom-class'});
positionClass string 'toast-top-right' Class on toast. this.toastrService.success('Hello world!', 'Toastr success!', {positionClass: 'custom-class'});
titleClass string 'toast-title' Class inside toast on title. this.toastrService.success('Hello world!', 'Toastr success!', {titleClass: 'custom-class'});
messageClass string 'toast-message' Class inside toast on message. this.toastrService.success('Hello world!', 'Toastr success!', {messageClass: 'custom-class'});
tapToDismiss boolean true Close on click. this.toastrService.success('Hello world!', 'Toastr success!', {tapToDismiss: false});

Events

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

Angular Notification / Toast - examples & customization


Individual config options MDB Pro component


        <!--Info message-->
        <a class="btn btn-info waves-light" (click)="showInfo()" mdbWavesEffect>Info message</a>
        <!--Warning message-->
        <a class="btn btn-warning waves-light" (click)="showWarning()" mdbWavesEffect>Warning message</a>
        <!--Success message-->
        <a class="btn btn-success waves-light" (click)="showSuccess()" mdbWavesEffect>Success message</a>
        <!--Error message-->
        <a class="btn btn-danger 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: '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 class="btn btn-success 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');
                });
              }
          }