Showing posts with label toaster. Show all posts
Showing posts with label toaster. Show all posts
ng2-toasty

ng2-toasty

October 27, 2017
Angular2 Toasty component shows growl-style alerts and messages for your app.

Installation

 npm install ng2-toasty --save  

Demo

Simple examples using ng2-dnd:
Online demo available here
Plunker demo available here

Usage

If you use SystemJS to load your files, you might have to update your config:
 System.config({  
   map: {  
     'ng2-toasty': 'node_modules/ng2-toasty/bundles/index.umd.js'  
   }  
 }); 

  1. Update the markup

  • Import style into your web page. Choose one of the following files;
    • style-default.css - Contains DEFAULT theme
    • style-bootstrap.css - Contains Bootstrap 3 theme
    • style-material.css - Contains Material Design theme
  • Assign the selected theme name [default, bootstrap, material] to the theme property of the instance of ToastyConfig.
  • Add <ng2-toasty></ng2-toasty> tag in template of your application component.

2. Import the ToastyModule

Import ToastyModule.forRoot() in the NgModule of your application. The forRoot method is a convention for modules that provide a singleton service.
 <pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> import {BrowserModule} from "@angular/platform-browser";   
  import {NgModule} from '@angular/core';   
  import {ToastyModule} from 'ng2-toasty';   
  @NgModule({   
   imports: [   
    BrowserModule,   
    ToastyModule.forRoot()   
   ],   
   bootstrap: [AppComponent]   
  })   
  export class AppModule {   
  }   
 </code></pre>  
If you have multiple NgModules and you use one as a shared NgModule (that you import in all of your other NgModules), don't forget that you can use it to export the ToastyModule that you imported in order to avoid having to import it multiple times.
 @NgModule({  
   imports: [  
     BrowserModule,  
     ToastyModule.forRoot()  
   ],  
   exports: [BrowserModule, ToastyModule],  
 })  
 export class SharedModule {  
 } 

Use the ToastyService for your application

  • Import ToastyService from ng2-toasty in your application code:

     

     import {Component} from '@angular/core';  
     import {ToastyService, ToastyConfig, ToastOptions, ToastData} from 'ng2-toasty';  
     @Component({  
       selector: 'app',  
       template: `  
         <div>Hello world</div>  
         <button (click)="addToast()">Add Toast</button>  
         <ng2-toasty></ng2-toasty>  
       `  
     })  
     export class AppComponent {  
       constructor(private toastyService:ToastyService, private toastyConfig: ToastyConfig) {   
         // Assign the selected theme name to the `theme` property of the instance of ToastyConfig.   
         // Possible values: default, bootstrap, material  
         this.toastyConfig.theme = 'material';  
       }  
       addToast() {  
         // Just add default Toast with title only  
         this.toastyService.default('Hi there');  
         // Or create the instance of ToastOptions  
         var toastOptions:ToastOptions = {  
           title: "My title",  
           msg: "The message",  
           showClose: true,  
           timeout: 5000,  
           theme: 'default',  
           onAdd: (toast:ToastData) => {  
             console.log('Toast ' + toast.id + ' has been added!');  
           },  
           onRemove: function(toast:ToastData) {  
             console.log('Toast ' + toast.id + ' has been removed!');  
           }  
         };  
         // Add see all possible types in one shot  
         this.toastyService.info(toastOptions);  
         this.toastyService.success(toastOptions);  
         this.toastyService.wait(toastOptions);  
         this.toastyService.error(toastOptions);  
         this.toastyService.warning(toastOptions);  
       }  
     } 

    4. How dynamically update title and message of a toast

    Here is an example of how to dynamically update message and title of individual toast:
     import {Component} from '@angular/core';  
     import {ToastyService, ToastyConfig, ToastyComponent, ToastOptions, ToastData} from 'ng2-toasty';  
     import {Subject, Observable, Subscription} from 'rxjs/Rx';  
     @Component({  
       selector: 'app',  
       template: `  
         <div>Hello world</div>  
         <button (click)="addToast()">Add Toast</button>  
         <ng2-toasty></ng2-toasty>  
       `  
     })  
     export class AppComponent {  
       getTitle(num: number): string {  
         return 'Countdown: ' + num;  
       }  
       getMessage(num: number): string {  
         return 'Seconds left: ' + num;  
       }  
       constructor(private toastyService:ToastyService) { }  
       addToast() {  
         let interval = 1000;  
         let timeout = 5000;  
         let seconds = timeout / 1000;  
         let subscription: Subscription;  
         let toastOptions: ToastOptions = {  
           title: this.getTitle(seconds),  
           msg: this.getMessage(seconds),  
           showClose: true,  
           timeout: timeout,  
           onAdd: (toast: ToastData) => {  
             console.log('Toast ' + toast.id + ' has been added!');  
             // Run the timer with 1 second iterval  
             let observable = Observable.interval(interval).take(seconds);  
             // Start listen seconds beat  
             subscription = observable.subscribe((count: number) => {  
               // Update title of toast  
               toast.title = this.getTitle(seconds - count - 1);  
               // Update message of toast  
               toast.msg = this.getMessage(seconds - count - 1);  
             });  
           },  
           onRemove: function(toast: ToastData) {  
             console.log('Toast ' + toast.id + ' has been removed!');  
             // Stop listenning  
             subscription.unsubscribe();  
           }  
         };  
         switch (this.options.type) {  
           case 'default': this.toastyService.default(toastOptions); break;  
           case 'info': this.toastyService.info(toastOptions); break;  
           case 'success': this.toastyService.success(toastOptions); break;  
           case 'wait': this.toastyService.wait(toastOptions); break;  
           case 'error': this.toastyService.error(toastOptions); break;  
           case 'warning': this.toastyService.warning(toastOptions); break;  
         }  
       }  
     } 

    5. How to close specific toast

     

     
    Here is an example of how to close an individual toast:
     import {Component} from '@angular/core';  
     import {ToastyService, ToastyConfig, ToastyComponent, ToastOptions, ToastData} from 'ng2-toasty';  
     import {Subject, Observable, Subscription} from 'rxjs/Rx';  
     @Component({  
       selector: 'app',  
       template: `  
         <div>Hello world</div>  
         <button (click)="addToast()">Add Toast</button>  
         <ng2-toasty></ng2-toasty>  
       `  
     })  
     export class AppComponent {  
       getTitle(num: number): string {  
         return 'Countdown: ' + num;  
       }  
       getMessage(num: number): string {  
         return 'Seconds left: ' + num;  
       }  
       constructor(private toastyService:ToastyService) { }  
       addToast() {  
         let interval = 1000;  
         let subscription: Subscription;  
         let toastOptions: ToastOptions = {  
           title: this.getTitle(0),  
           msg: this.getMessage(0),  
           showClose: true,  
           onAdd: (toast: ToastData) => {  
             console.log('Toast ' + toast.id + ' has been added!');  
             // Run the timer with 1 second iterval  
             let observable = Observable.interval(interval);  
             // Start listen seconds beat  
             subscription = observable.subscribe((count: number) => {  
               // Update title of toast  
               toast.title = this.getTitle(count);  
               // Update message of toast  
               toast.msg = this.getMessage(count);  
               // Extra condition to hide Toast after 10 sec  
               if (count > 10) {  
                 // We use toast id to identify and hide it  
                 this.toastyService.clear(toast.id);  
               }  
             });  
           },  
           onRemove: function(toast: ToastData) {  
             console.log('Toast ' + toast.id + ' has been removed!');  
             // Stop listenning  
             subscription.unsubscribe();  
           }  
         };  
         switch (this.options.type) {  
           case 'default': this.toastyService.default(toastOptions); break;  
           case 'info': this.toastyService.info(toastOptions); break;  
           case 'success': this.toastyService.success(toastOptions); break;  
           case 'wait': this.toastyService.wait(toastOptions); break;  
           case 'error': this.toastyService.error(toastOptions); break;  
           case 'warning': this.toastyService.warning(toastOptions); break;  
         }  
       }  
     } 

    6. Customize the ng2-toasty for your application in template

    You can use the following properties to customize the ng2-toasty component in your template:
  • position - The window position where the toast pops up. Default value is bottom-right. Possible values: bottom-right, bottom-left, top-right, top-left, top-center, bottom-center, center-center Example:
  •  <ng2-toasty [position]="'top-center'"></ng2-toasty>  
    


Note: Special thanks to Sergey Akopkokhyants

Contact: akserg@gmail.com

Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.
Angular2-Toaster

Angular2-Toaster

October 27, 2017
angular2-toaster is an asynchronous, non-blocking, Ahead of Time Compilation-supported Angular Toaster Notification library largely based off of AngularJS-Toaster.

Version ^4.0.0 now supports @angular/animations, which is a breaking change. Please read both the Getting Started and Animations sections before upgrading.

Demo

A dynamic Angular and Typescript demo can be found at this plunker.

Getting Started

Installation:

 npm install angular2-toaster  

Import CSS

Copy or Link CSS

 <link rel="stylesheet" type="text/css" href="/node_modules/angular2-toaster/toaster.css" />  

Import CSS with Sass or Less

 @import 'node_modules/angular2-toaster/toaster';  

Import Library

Import via SystemJS

Within the map property of the systemjs.config file, add mappings for angular, rxjs (which is a dependency), and the angular2-toaster bundled umd file:
 map: {  
    // angular bundles  
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js',  
    // ...  
    // other libraries  
    'rxjs': 'npm:rxjs',  
    'angular2-toaster': 'npm:angular2-toaster/bundles/angular2-toaster.umd.js'  

Import via Webpack

Simply follow the Getting Started instructions to import the library.

Getting Started With Default Configuration - NgModule (Recommended):

 import {NgModule, Component} from '@angular/core';  
 import {BrowserAnimationsModule} from '@angular/platform-browser/animations';  
 import {ToasterModule, ToasterService} from 'angular2-toaster';  
 import {Root} from './root.component'  
 @NgModule({  
   imports: [BrowserAnimationsModule, ToasterModule],  
   declarations: [Root],  
   providers: [],  
   bootstrap: [Root]  
 })  
 @Component({  
   selector: 'root',  
   template: `  
       <toaster-container></toaster-container>  
       <button (click)="popToast()">pop toast</button>`  
 })  
 export class Root {  
   private toasterService: ToasterService;  
   constructor(toasterService: ToasterService) {  
     this.toasterService = toasterService;  
   }  
   popToast() {  
     this.toasterService.pop('success', 'Args Title', 'Args Body');  
   }  
 }  

Getting Started with Default Configuration - Manual Component Inclusion:

 import {Component} from '@angular/core';  
 import {BrowserAnimationsModule} from '@angular/platform-browser/animations';  
 import {ToasterContainerComponent, ToasterService} from 'angular2-toaster';  
 @Component({  
   selector: 'root',  
   imports: [BrowserAnimationsModule],  
   directives: [ToasterContainerComponent],  
   providers: [ToasterService],  
   template: `  
     <toaster-container></toaster-container>  
     <button (click)="popToast()">pop toast</button>`  
 })  
 class Root {  
   private toasterService: ToasterService;  
   constructor(toasterService: ToasterService) {  
     this.toasterService = toasterService;    
   }  
   popToast() {  
     this.toasterService.pop('success', 'Args Title', 'Args Body');  
   }  
 }  
 bootstrap(Root);  
 Getting Started with Configuration Override:  
 import {Component} from '@angular/core';  
 import {BrowserAnimationsModule} from '@angular/platform-browser/animations';  
 import {ToasterContainerComponent, ToasterService, ToasterConfig} from 'angular2-toaster';  
 @Component({  
   selector: 'root',  
   imports: [BrowserAnimationsModule],  
   directives: [ToasterContainerComponent],  
   providers: [ToasterService],  
   template: `  
     <toaster-container [toasterconfig]="toasterconfig">  
     </toaster-container>  
     <button (click)="popToast()">pop toast</button>`  
 })  
 class Root {  
   private toasterService: ToasterService;  
   constructor(toasterService: ToasterService) {  
     this.toasterService = toasterService;    
   }  
   public toasterconfig : ToasterConfig =   
     new ToasterConfig({  
       showCloseButton: true,   
       tapToDismiss: false,   
       timeout: 0  
     });  
   popToast() {  
     this.toasterService.pop('success', 'Args Title', 'Args Body');  
   }  
 }  
 bootstrap(Root);  

Asynchronous vs Synchronous ToasterService

ToasterService exposes both a synchronous and asynchronous pop method in the form of pop() and popAsync() respectively.
pop() returns a concrete Toast instance after the toastId property has been hydrated and the toast has been added to all receiving containers.
popAsync() returns a hot Observable<Toast> that may be subscribed to to receive multiple toast updates.

Customize Toast arguments in pop

 var toast: Toast = {  
   type: 'success',  
   title: 'close button',  
   showCloseButton: true  
 };  
 this.toasterService.pop(toast);  

Clear Existing Toast

ToasterService exposes a clear function that accepts two optional parameters: toastId and toastContainerId.
These parameters can be used to clear toasts by specific id, by container id, by both, or by neither. If both parameters are omitted, all toasts in all containers will be removed.
 var toast = this.toasterService.pop('success', 'title', 'body');  
 this.toasterService.clear(toast.toastId, toast.toastContainerId);  

Animations

Starting with version 4.0.0 and greater, Animation configuration is required, as described in the Getting Started section.
To add animations:
  • Install the @angular/animations npm package via npm install @angular/animations.
  • Add the BrowserAnimationsModule to your root module
  •  import {NgModule, Component} from '@angular/core';  
     import {BrowserAnimationsModule} from '@angular/platform-browser/animations';  
     import {ToasterModule} from 'angular2-toaster';  
     @NgModule({  
       imports: [BrowserAnimationsModule, ToasterModule],  
       ...  
    
If you want to avoid bringing in an additional module solely for the sake of animations, you can explicitly configure angular2-toaster to ignore animations. To do so, import the NoopAnimationsModule instead:
 import {NoopAnimationsModule} from '@angular/platform-browser/animations';  
 import {ToasterModule} from 'angular2-toaster';  
 @NgModule({  
   imports: [NoopAnimationsModule, ToasterModule],  
   ...  
Angular Animations require browsers that support the Web Animations Standard.
If you need to target a non-supported browser, a polyfill is required.

Configurable Options

Animations

There are five animation styles that can be applied via the toasterconfig animation property: 'fade', 'flyLeft', 'flyRight', 'slideDown', and 'slideUp'. Any other value will disable animations.
 template:   
   `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
 public toasterconfig : ToasterConfig =   
   new ToasterConfig({animation: 'fade'});  

Limit

Limit is defaulted to null, meaning that there is no maximum number of toasts that are defined before the toast container begins removing toasts when a new toast is added.
To change this behavior, pass a "limit" option to the config:
 template:   
   `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
 public toasterconfig : ToasterConfig =   
   new ToasterConfig({limit: 5});  

Tap to Dismiss

By default, the tapToDismiss option is set to true, meaning that if a toast is clicked anywhere on the toast body, the toast will be dismissed. This behavior can be overriden in the config so that if set to false, the toast will only be dismissed if the close button is defined and clicked:
 template:   
   `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
 public toasterconfig : ToasterConfig =   
   new ToasterConfig({tapToDismiss: false});  

Close Button

The Close Button's visibility can be configured at three different levels:

  • Globally in the config for all toast types:
     template:   
       `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
     public toasterconfig : ToasterConfig =   
       new ToasterConfig({showCloseButton: true});  
    
  • Per info-class type: By passing the close-button configuration as an object instead of a boolean, you can specify the global behavior an info-class type should have.
     template:   
       `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
     public toasterconfig : ToasterConfig =   
       new ToasterConfig({  
         showCloseButton: { 'warning': true, 'error': false }  
       });  
    
    If a type is not defined and specified, the default behavior for that type is false.
  • Per toast constructed via Toast object creation:
 var toast : Toast = {  
   type: 'error',  
   title: 'Title text',  
   body: 'Body text',  
   showCloseButton: true  
 };  
 this.toasterService.pop(toast);  
This option is given the most weight and will override the global configurations for that toast. However, it will not persist to other toasts of that type and does not alter or pollute the global configuration.

Close Html

The close button html can be overridden either globally or per toast call.
  • Globally:
     template:   
       `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
     public toasterconfig : ToasterConfig =   
       new ToasterConfig({  
         closeHtml: '<button>Close</button>'  
       });  
    
  • Per toast:
       var toast : Toast = {  
         type: 'error',  
         title: 'Title text',  
         body: 'Body text',  
         showCloseButton: true,  
         closeHtml: '<button>Close</button>'  
       };  
       this.toasterService.pop(toast);  
    

Newest Toasts on Top

The newestOnTop option is defaulted to true, adding new toasts on top of other existing toasts. If changed to false via the config, toasts will be added to the bottom of other existing toasts.
 template:   
   `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
 public toasterconfig : ToasterConfig =   
   new ToasterConfig({newestOnTop: false});  

Timeout

By default, toasts have a timeout setting of 5000, meaning that they are removed after 5000 milliseconds.
If the timeout is set to anything other than a number greater than 0, the toast will be considered "sticky" and will not automatically dismiss.
The timeout can be configured at three different levels:
  • Globally in the config for all toast types:
     template:   
      `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
     public toasterconfig : ToasterConfig =   
        new ToasterConfig({timeout: 2000});  
    
  • Per info-class type: By passing the timeout config option as an object instead of a number, you can specify the global behavior an info-class type should have.
     template:   
      `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
     public toasterconfig : ToasterConfig =   
       new ToasterConfig({timeout: {error:1000});  
    
If a type is not defined and specified, a timeout will not be applied, making the toast "sticky".
Per toast constructed via toaster.pop('success', "title", "text"):
 var toast : Toast = {  
   type: 'error',  
   title: 'Title text',  
   body: 'Body text',  
   showCloseButton: true,  
   closeHtml: '<button>Close</button>'  
 };  
 this.toasterService.pop(toast);  

Prevent Timeout on Mouseover

By default, all toasts are dismissed when their timer expires, even if you mouse over the toast. This can be overriden via the container's config.
 template:   
   `<toaster-container [toasterconfig]="toasterconfig"></toaster-container>`  
 public toasterconfig : ToasterConfig =   
   new ToasterConfig({mouseoverTimerStop: false});  

Body Output Type

There are three different types of body renderings that can be passed via the toast.bodyOutputType argument: 'Default', 'TrustedHtml', and 'Component'. If a bodyOutputType is not provided, it will be defaulted to 'Default'.
  • Default: The body argument will be directly interpolated as text content. If html is passed in the body argument, it will be encoded and rendered as text.
  • TrustedHtml: The body argument will be parsed and rendered as html content.
     import {BodyOutputType} from 'angular2-toaster';  
     var toast : Toast = {  
       type: 'error',  
       title: 'Title text',  
       body: '<h4>Body text</h4>',  
       bodyOutputType: BodyOutputType.TrustedHtml  
     };  
     this.toasterService.pop(toast);  
    
  • Component: The body argument is the name of the component class to be rendered as the content of the toast.
     import {BodyOutputType} from 'angular2-toaster';  
     @Component({  
      selector: 'dynamic-component',  
      template: `<div>loaded via component</div>`  
     })  
     class DynamicComponent { }  
     var toast : Toast = {  
       type: 'error',  
       title: 'Title text',  
       body: DynamicComponent,  
       bodyOutputType: BodyOutputType.Component  
     };  
     this.toasterService.pop(toast);  
    
The Component BodyOutputType offers the additional flexibilty of attaching the toast instance to your component. It is recommended that you expose a public property on your component for type safe access to the toast instance if you need to consume it inside of your component. Mutation of the toast instance is not recommended.

On Show Callback

An onShow callback function can be attached to each toast instance. The callback will be invoked upon toast add.
 var toast: Toast = {  
  type: 'success',  
  title: 'parent',  
  onShowCallback: (toast) => this.toasterService.pop('success', 'invoked from ' + toast.title + ' onShow callback')   
 };  
 this.toasterService.pop(toast);  

On Hide Callback

An onHide callback function can be attached to each toast instance. The callback will be invoked upon toast removal.
 var toast: Toast = {  
  type: 'success',  
  title: 'parent',  
  onHideCallback: (toast) => this.toasterService.pop('success', 'invoked from ' + toast.title + ' onHide callback')   
 };  
 this.toasterService.pop(toast);  


Note: Special thanks to Stabzs

Disclaimer: The blog is created to share angular directives information to geek, curious Angular Developers.