18.0.0 • Published 4 months ago

ngx-toastr v18.0.0

Weekly downloads
227,303
License
MIT
Repository
github
Last release
4 months ago

DEMO: https://ngx-toastr.vercel.app

Features

  • Toast Component Injection without being passed ViewContainerRef
  • No use of *ngFor. Fewer dirty checks and higher performance.
  • AoT compilation and lazy loading compatible
  • Component inheritance for custom toasts
  • SystemJS/UMD rollup bundle
  • Animations using Angular's Web Animations API
  • Output toasts to an optional target directive

Dependencies

Latest version available for each version of Angular

ngx-toastrAngular
13.2.110.x 11.x
14.3.012.x 13.x
15.2.214.x.
16.2.015.x
17.0.216.x
current>= 17.x

Install

npm install ngx-toastr --save

@angular/animations package is a required dependency for the default toast

npm install @angular/animations --save

Don't want to use @angular/animations? See Setup Without Animations.

Setup

step 1: add css

  • copy toast css to your project.
  • If you are using sass you can import the css.
// regular style toast
@import 'ngx-toastr/toastr';

// bootstrap style toast
// or import a bootstrap 4 alert styled design (SASS ONLY)
// should be after your bootstrap imports, it uses bs4 variables, mixins, functions
@import 'ngx-toastr/toastr-bs4-alert';

// if you'd like to use it without importing all of bootstrap it requires
@import 'bootstrap/scss/functions';
@import 'bootstrap/scss/variables';
@import 'bootstrap/scss/mixins';
// bootstrap 4
@import 'ngx-toastr/toastr-bs4-alert';
// boostrap 5
@import 'ngx-toastr/toastr-bs5-alert';
  • If you are using angular-cli you can add it to your angular.json
"styles": [
  "styles.scss",
  "node_modules/ngx-toastr/toastr.css" // try adding '../' if you're using angular cli before 6
]

step 2: add ToastrModule to app NgModule, or provideToastr to providers, make sure you have BrowserAnimationsModule (or provideAnimations) as well.

  • Module based
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ToastrModule } from 'ngx-toastr';

@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule, // required animations module
    ToastrModule.forRoot(), // ToastrModule added
  ],
  bootstrap: [App],
  declarations: [App],
})
class MainModule {}
  • Standalone
import { AppComponent } from './src/app.component';
import { provideAnimations } from '@angular/platform-browser/animations';

import { provideToastr } from 'ngx-toastr';

bootstrapApplication(AppComponent, {
  providers: [
    provideAnimations(), // required animations providers
    provideToastr(), // Toastr providers
  ]
});

Use

import { ToastrService } from 'ngx-toastr';

@Component({...})
export class YourComponent {
  constructor(private toastr: ToastrService) {}

  showSuccess() {
    this.toastr.success('Hello world!', 'Toastr fun!');
  }
}

Options

There are individual options and global options.

Individual Options

Passed to ToastrService.success/error/warning/info/show()

OptionTypeDefaultDescription
toastComponentComponentToastAngular component that will be used
closeButtonbooleanfalseShow close button
timeOutnumber5000Time to live in milliseconds
extendedTimeOutnumber1000Time to close after a user hovers over toast
disableTimeOutboolean \| 'timeOut' \| 'extendedTimeOut'falseDisable both timeOut and extendedTimeOut when set to true. Allows specifying which timeOut to disable, either: timeOut or extendedTimeOut
easingstring'ease-in'Toast component easing
easeTimestring | number300Time spent easing
enableHtmlbooleanfalseAllow html in message
newestOnTopbooleantrueNew toast placement
progressBarbooleanfalseShow progress bar
progressAnimation'decreasing' \| 'increasing''decreasing'Changes the animation of the progress bar.
toastClassstring'ngx-toastr'CSS class(es) for toast
positionClassstring'toast-top-right'CSS class(es) for toast container
titleClassstring'toast-title'CSS class(es) for inside toast on title
messageClassstring'toast-message'CSS class(es) for inside toast on message
tapToDismissbooleantrueClose on click
onActivateTickbooleanfalseFires changeDetectorRef.detectChanges() when activated. Helps show toast from asynchronous events outside of Angular's change detection

Setting Individual Options

success, error, info, warning take (message, title, ToastConfig) pass an options object to replace any default option.

this.toastrService.error('everything is broken', 'Major Error', {
  timeOut: 3000,
});

Global Options

All individual options can be overridden in the global options to affect all toasts. In addition, global options include the following options:

OptionTypeDefaultDescription
maxOpenednumber0Max toasts opened. Toasts will be queued. 0 is unlimited
autoDismissbooleanfalseDismiss current toast when max is reached
iconClassesobjectsee belowClasses used on toastr service methods
preventDuplicatesbooleanfalseBlock duplicate messages
countDuplicatesbooleanfalseDisplays a duplicates counter (preventDuplicates must be true). Toast must have a title and duplicate message
resetTimeoutOnDuplicatebooleanfalseReset toast timeout on duplicate (preventDuplicates must be true)
includeTitleDuplicatesbooleanfalseInclude the title of a toast when checking for duplicates (by default only message is compared)
iconClasses defaults
iconClasses = {
  error: 'toast-error',
  info: 'toast-info',
  success: 'toast-success',
  warning: 'toast-warning',
};

Setting Global Options

Pass values to ToastrModule.forRoot() or provideToastr() to set global options.

  • Module based
// root app NgModule
imports: [
  ToastrModule.forRoot({
    timeOut: 10000,
    positionClass: 'toast-bottom-right',
    preventDuplicates: true,
  }),
],
  • Standalone
import { AppComponent } from './src/app.component';
import { provideAnimations } from '@angular/platform-browser/animations';

import { provideToastr } from 'ngx-toastr';

bootstrapApplication(AppComponent, {
  providers: [
    provideToastr({
      timeOut: 10000,
      positionClass: 'toast-bottom-right',
      preventDuplicates: true,
    }), 
  ]
});

Toastr Service methods return:

export interface ActiveToast {
  /** Your Toast ID. Use this to close it individually */
  toastId: number;
  /** the title of your toast. Stored to prevent duplicates if includeTitleDuplicates set */
  title: string;
  /** the message of your toast. Stored to prevent duplicates */
  message: string;
  /** a reference to the component see portal.ts */
  portal: ComponentRef<any>;
  /** a reference to your toast */
  toastRef: ToastRef<any>;
  /** triggered when toast is active */
  onShown: Observable<any>;
  /** triggered when toast is destroyed */
  onHidden: Observable<any>;
  /** triggered on toast click */
  onTap: Observable<any>;
  /** available for your use in custom toast */
  onAction: Observable<any>;
}

Put toasts in your own container

Put toasts in a specific div inside your application. This should probably be somewhere that doesn't get deleted. Add ToastContainerModule to the ngModule where you need the directive available. Make sure that your container has an aria-live="polite" attribute, so that any time a toast is injected into the container it is announced by screen readers.

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

import { ToastrModule, ToastContainerModule } from 'ngx-toastr';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,

    ToastrModule.forRoot({ positionClass: 'inline' }),
    ToastContainerModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Add a div with toastContainer directive on it.

import { Component, OnInit, ViewChild } from '@angular/core';

import { ToastContainerDirective, ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-root',
  template: `
    <h1><a (click)="onClick()">Click</a></h1>
    <div aria-live="polite" toastContainer></div>
  `,
})
export class AppComponent implements OnInit {
  @ViewChild(ToastContainerDirective, { static: true })
  toastContainer: ToastContainerDirective;

  constructor(private toastrService: ToastrService) {}
  ngOnInit() {
    this.toastrService.overlayContainer = this.toastContainer;
  }
  onClick() {
    this.toastrService.success('in div');
  }
}

Functions

Clear

Remove all or a single toast by optional id

toastrService.clear(toastId?: number);
Remove

Remove and destroy a single toast by id

toastrService.remove(toastId: number);

SystemJS

If you are using SystemJS, you should also adjust your configuration to point to the UMD bundle.

In your SystemJS config file, map needs to tell the System loader where to look for ngx-toastr:

map: {
  'ngx-toastr': 'node_modules/ngx-toastr/bundles/ngx-toastr.umd.min.js',
}

Setup Without Animations

If you do not want to include @angular/animations in your project you can override the default toast component in the global config to use ToastNoAnimation instead of the default one.

In your main module (ex: app.module.ts)

import { ToastrModule, ToastNoAnimation, ToastNoAnimationModule } from 'ngx-toastr';

@NgModule({
  imports: [
    // ...

    // BrowserAnimationsModule no longer required
    ToastNoAnimationModule.forRoot(),
  ],
  // ...
})
class AppModule {}

That's it! Animations are no longer required.

Using A Custom Toast

Create your toast component extending Toast see the demo's pink toast for an example https://github.com/scttcper/ngx-toastr/blob/master/src/app/pink.toast.ts

import { ToastrModule } from 'ngx-toastr';

@NgModule({
  imports: [
    ToastrModule.forRoot({
      toastComponent: YourToastComponent, // added custom toast!
    }),
  ],
  bootstrap: [App],
  declarations: [App, YourToastComponent], // add!
})
class AppModule {}

FAQ

  1. ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked\ When opening a toast inside an angular lifecycle wrap it in setTimeout
ngOnInit() {
    setTimeout(() => this.toastr.success('sup'))
}
  1. Change default icons (check, warning sign, etc)\ Overwrite the css background-image: https://github.com/scttcper/ngx-toastr/blob/master/src/lib/toastr.css.
  2. How do I use this in an ErrorHandler?\ See: https://github.com/scttcper/ngx-toastr/issues/179.
  3. How can I translate messages?\ See: https://github.com/scttcper/ngx-toastr/issues/201.
  4. How to handle toastr click/tap action?

    showToaster() {
      this.toastr.success('Hello world!', 'Toastr fun!')
        .onTap
        .pipe(take(1))
        .subscribe(() => this.toasterClickedHandler());
    }
    
    toasterClickedHandler() {
      console.log('Toastr clicked');
    }
  5. How to customize styling without overridding defaults?\ Add multiple CSS classes separated by a space:

    toastClass: 'yourclass ngx-toastr'

    See: https://github.com/scttcper/ngx-toastr/issues/594.

Previous Works

toastr original toastr\ angular-toastr AngularJS toastr\ notyf notyf (css)

License

MIT


GitHub @scttcper  ·  Twitter @scttcper

waafipay_adminportal.pkg@dilshan247/portal-libcustomermanagementcb-customermagementcb-masterservicecb-masterservice1cb-ms@epicor/kineticlaji-frontqool-master-librarybonee-shared-lib@zdavy4k/headerangular-mat-uploaderbee-authbee-common-workspace@pegaswork/core@frannca/ngx-loginsteentjes-ictangular-inputv6-angularv6-testkc-layoutsportcrmeviewer-libgsa-sam-sam-formlydynamicform-uiorganization-registrationv2wlf-libscapiter-ui-newcamotecustom-grid-lib@infinitebrahmanuniverse/nolb-ngx-t@everything-registry/sub-chunk-2288kruzer-uifrontend-backofficeeviewer7-lib@mstechusa/eviewer7-clicloutregulars-frontendfiscalia-libreriasnpm-dz-hell-to-heroebbsf-controlsbbsf-utilitiesas-ae-11appcamundanotificationasset-tracking-appcbmsclient-users@bellese/angular-design-systembonee-client-corecomponent-utilitycombobox-custombs3-breakpointbrio-modulesbrio-modules1black-dashboard-angularcalendar-poc@bnsights-test/test-utilities@bnsights/bbsf-utilitiesbnsights-control-librarybnsights-librarybnsights-library-pagesbnsights-utilities-librarycancel-workspacecamundanotificationcamundanotificationwebappcamundawebappnotification@brayit/bray-iiot-gateway@capiter-tech/capiter-ui-componentscapiter-ui-componentspygepurenet-authenticationpowerflex-componentsorion-apppom-gestion-humana-siportkonnectcargoprime-ngx-arpathway-dashboardpers-apppc-packagephoenix-ui-corepib-frontend-frameworkpms-mf-boilerplatepms-mf-corepocworkspacepod-edit-template-component-uipedretti-shared-npmsafe-notificationreport-generatese-ui-toolkit-testvr-theme-library-npmtrackwizz-ui-lib-projtesting9vx-teste-mark2vx-teste-mark3vvvvwavemaker-ng-runtime-newwm_codegen_angular_appuserchat-libraryuserchat-library-ionicuserchat-library-ionic1utilscore-ar
18.0.0

4 months ago

17.0.2

11 months ago

17.0.1

11 months ago

17.0.0

11 months ago

16.1.1

12 months ago

16.2.0

11 months ago

16.1.0

1 year ago

15.2.1

1 year ago

15.2.2

1 year ago

16.0.2

1 year ago

16.0.1

1 year ago

16.0.0

1 year ago

15.1.0

2 years ago

15.2.0

1 year ago

15.0.0

2 years ago

14.2.3

2 years ago

14.2.4

2 years ago

14.3.0

2 years ago

14.2.2

2 years ago

14.2.0

2 years ago

14.2.1

2 years ago

14.1.4

2 years ago

14.1.1

3 years ago

14.1.2

3 years ago

14.1.3

3 years ago

14.1.0

3 years ago

14.0.0

3 years ago

13.2.1

3 years ago

13.2.0

3 years ago

13.1.0

3 years ago

13.0.1

3 years ago

13.0.0

4 years ago

12.1.0

4 years ago

12.0.1

4 years ago

12.0.0

4 years ago

11.3.3

4 years ago

11.3.1

4 years ago

11.3.2

4 years ago

11.3.0

4 years ago

11.2.1

4 years ago

11.2.0

4 years ago

11.1.2

4 years ago

11.1.1

4 years ago

11.1.0

4 years ago

11.0.0

5 years ago

10.2.0

5 years ago

10.1.0

5 years ago

10.0.4

5 years ago

10.0.3

5 years ago

10.0.2

5 years ago

10.0.1

5 years ago

10.0.0

5 years ago

9.2.0

5 years ago

9.1.2

5 years ago

9.1.1

5 years ago

9.1.0

6 years ago

9.0.2

6 years ago

9.0.1

6 years ago

9.0.0

6 years ago

8.10.2

6 years ago

8.10.1

6 years ago

8.10.0

6 years ago

8.9.1

6 years ago

8.9.0

6 years ago

8.8.0

6 years ago

8.7.3

6 years ago

8.7.2

6 years ago

8.7.1

6 years ago

8.7.0

6 years ago

8.6.0

6 years ago

8.5.1

6 years ago

8.5.0

6 years ago

8.4.0

6 years ago

8.3.2

6 years ago

8.3.1

6 years ago

8.3.0

6 years ago

8.2.1

6 years ago

8.2.0

6 years ago

8.1.1

6 years ago

8.1.0

6 years ago

8.0.0

6 years ago

7.1.0

6 years ago

6.4.1-beta.0

6 years ago

7.0.2

6 years ago

7.0.1

6 years ago

7.0.0

6 years ago

7.0.0-beta.1

6 years ago

7.0.0-beta.0

6 years ago

6.5.0

6 years ago

6.4.0

6 years ago

6.3.0

7 years ago

6.2.1

7 years ago

6.2.0

7 years ago

6.1.5

7 years ago

6.1.4

7 years ago

6.1.3

7 years ago

6.1.2

7 years ago

6.1.1

7 years ago

6.1.0

7 years ago

6.0.1

7 years ago

6.0.0

7 years ago

6.0.0-beta.2

7 years ago

6.0.0-beta.1

7 years ago

5.3.1

7 years ago

5.3.0

7 years ago

5.2.5

7 years ago

5.2.4

7 years ago

5.2.3

7 years ago

5.2.2

7 years ago

5.2.1

7 years ago

5.2.0

7 years ago

5.1.0

7 years ago

5.0.7

7 years ago

5.0.6

7 years ago

5.0.5

7 years ago

5.0.3

7 years ago

4.4.1

7 years ago

4.4.0

7 years ago

5.0.2

7 years ago

5.0.1

7 years ago

5.0.0

7 years ago

4.3.0

7 years ago

4.2.1

7 years ago

4.2.0

7 years ago