UI Components / Feedback

Toast Notifications requires the inclusion of ng2-toastr, an external resource used to create Toast Notifications in Angular 2 applications.

Below is a simple Angular 4.1.2 app providing buttons to trigger each of the five toast notification options.

The most important piece to remember is that ng2-toastr requires importing BrowserAnimationsModule into the module making using of the library (for Angular 4 apps).

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ToastModule, ToastOptions } from 'ng2-toastr/ng2-toastr';

import { AppComponent } from './component';

export class CustomOptions extends ToastOptions {
  animate = 'fade';
  dismiss = 'auto';
  showCloseButton = true;
  newestOnTop = true;
  enableHTML = true;
}

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ToastModule.forRoot()
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    {
      provide: ToastOptions,
      useClass: CustomOptions
    }
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {}
import { Component, ViewContainerRef } from '@angular/core';

import { ToastsManager } from 'ng2-toastr/ng2-toastr';

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

  constructor(private toastr: ToastsManager, vRef: ViewContainerRef) {
    this.toastr.setRootViewContainerRef(vRef);
  }

  showToast(toastType) {
    let options = { toastLife: 10000 },
        message = 'I am a toast notitification with a very, very, very long message!';
    switch (toastType) {
      case 'success':
        this.toastr.success(message, 'Success!', options);
        break;
      case 'error':
        this.toastr.error(message, 'Error!', options);
        break;
      case 'warning':
        this.toastr.warning(message, 'Warning!', options);
        break;
      case 'info':
        this.toastr.info(message, 'Info!', options);
        break;
      case 'custom':
        this.toastr.custom(message, 'Custom!', options);
        break;
    }
    return true;
  }
}
<div class="container text-center">
  <a (click)="showToast('success')" class="btn btn-success">Success</a>
  <a (click)="showToast('error')" class="btn btn-danger">Error</a>
  <a (click)="showToast('warning')" class="btn btn-warning">Warning</a>
  <a (click)="showToast('info')" class="btn btn-secondary">Info</a>
  <a (click)="showToast('custom')" class="btn btn-default">Custom</a>
</div>