ngx-toastr

repository·master·Indexed 25 days ago

https://github.com/scttcper/ngx-toastr

An Angular library for displaying high-performance toast notifications. It supports AoT, lazy loading, and flexible styling options including Bootstrap 4 and 5 integration. The library provides ToastrService for triggering notifications, Global and Individual configuration options, and support for custom toast components by extending the ToastBase class.

Tokens
6.7K
Snippets
18
Records
33
Agent score
80%

What's inside ngx-toastr

  1. Use a custom toast component

    master

    To use a custom UI for your toasts, create a component that extends the base Toast class and register it in the ToastrModule.forRoot() configuration using the toastComponent key. Ensure your custom component is also declared in your @NgModule declarations.

    import { ToastrModule } from 'ngx-toastr';
    
    @NgModule({
      imports: [
        ToastrModule.forRoot({
          toastComponent: YourToastComponent, // added custom toast!
        }),
      ],
      bootstrap: [App],
      declarations: [App, YourToastComponent], // add!
    })
    class AppModule {}
  2. Output toasts to a custom container

    master

    By default, toasts are injected into a global container. To output toasts into a specific element within your application:

    1. Add ToastContainerDirective to your NgModule declarations/imports.
    2. Add the toastContainer directive to a div in your template. Ensure the div has aria-live="polite" for accessibility.
    3. In your component, use viewChild to get the ToastContainerDirective and assign it to toastrService.overlayContainer during ngOnInit.
    // 1. Register directive in Module
    @NgModule({
      imports: [
        ToastrModule.forRoot({ positionClass: 'inline' }),
        ToastContainerDirective,
      ],
      // ...
    })
    export class AppModule {}
    
    // 2. Use in Component
    @Component({
      selector: 'app-root',
      template: `
        <h1 (click)="onClick()">Click</h1>
        <div aria-live="polite" toastContainer></div>
      `,
    })
    export class AppComponent implements OnInit {
      toastContainer = viewChild(ToastContainerDirective, { static: true });
      toastrService = inject(ToastrService);
    
      ngOnInit() {
        this.toastrService.overlayContainer = this.toastContainer;
      }
      onClick() {
        this.toastrService.success('in div');
      }
    }
  3. Initialize ngx-toastr in an Angular application

    master

    Depending on your application architecture, use either ToastrModule.forRoot() for Module-based apps or provideToastr() for Standalone applications.

    // Module-based setup
    import { ToastrModule } from 'ngx-toastr';
    
    @NgModule({
      imports: [
        ToastrModule.forRoot(),
      ],
      // ...
    })
    class MainModule {}
    // Standalone setup
    import { provideToastr } from 'ngx-toastr';
    
    bootstrapApplication(AppComponent, {
      providers: [
        provideToastr(),
      ]
    });
  4. Setup ngx-toastr without animations

    master

    If you want to disable animations, you can use ToastNoAnimationModule instead of the standard ToastrModule. This overrides the default toast component globally with ToastNoAnimation.

    import { ToastNoAnimationModule } from 'ngx-toastr';
    
    @NgModule({
      imports: [
        // ...
        ToastNoAnimationModule.forRoot(),
      ],
      // ...
    })
    class AppModule {}
  5. Configure ngx-toastr CSS

    master

    You must include the toastr CSS in your project for the toasts to render correctly. You have three main options:

    1. Directly in angular.json: Add the path to your styles array.
    2. SASS Import: Import the styles directly in your SCSS files.
    3. Bootstrap Styles: Use specialized imports for Bootstrap 4 or 5 styled toasts (requires Bootstrap SCSS variables/mixins).
    "styles": [
      "styles.scss",
      "node_modules/ngx-toastr/toastr.css"
    ]
    // regular style toast
    @import 'ngx-toastr/toastr';
    
    // bootstrap style toast (SASS ONLY)
    @import 'ngx-toastr/toastr-bs4-alert';
    // or
    @import 'ngx-toastr/toastr-bs5-alert';
  6. Configure Global Toast Options

    master

    Set default options for all toasts by passing a configuration object to ToastrModule.forRoot() or provideToastr() during application initialization.

    // Module based
    ToastrModule.forRoot({
      timeOut: 10000,
      positionClass: 'toast-bottom-right',
      preventDuplicates: true,
    })
    
    // Standalone
    provideToastr({
      timeOut: 10000,
      positionClass: 'toast-bottom-right',
      preventDuplicates: true,
    })
  7. Customize toast styling with CSS classes

    master

    To add custom styling without overriding the default ngx-toastr classes, provide multiple CSS classes separated by a space in the toastClass configuration option.

    toastClass: 'yourclass ngx-toastr'
  8. How ToastBase manages toast lifecycle and interactions

    master

    ToastBase implements a sophisticated lifecycle for toasts using Angular signals and RxJS subscriptions:

    1. Activation: When the toast is activated, it sets its state to 'active' and initiates the timeOut timer. If progressBar is enabled, it starts an interval to update the width signal.
    2. Timeout Management:
      • Standard Timeout: Uses options.timeOut to trigger remove().
      • Stick Around: On mouseenter, the current timeout is cleared to keep the toast visible.
      • Delayed Hide: On mouseleave, if configured, the toast uses extendedTimeOut to determine when to hide.
    3. Removal: The remove() method sets the state to 'removed' and schedules the actual removal from the ToastrService after the animation time has passed.
    4. Progress Bar: The updateProgress() method calculates the remaining time relative to the total timeOut and updates the width signal. It supports both default and 'increasing' progress animation modes.
  9. Use ToastNoAnimationModule to disable toast animations

    master
    To use ngx-toastr without animations, import and initialize the ToastNoAnimationModule using its forRoot method. This replaces the default animated toast component with ToastNoAnimation globally. You can pass a partial GlobalConfig object to forRoot to customize settings while maintaining the no-animation behavior.
  10. Configure ngx-toastr using provideToastr

    master

    In modern Angular applications, use the provideToastr function within your application configuration (e.g., in app.config.ts or the bootstrap function) to set up the toastr service and its global configuration.

    Passing a configuration object to provideToastr allows you to override default settings such as timeOut and positionClass. The function returns EnvironmentProviders, making it suitable for standalone application bootstrapping.

    import { provideToastr } from 'ngx-toastr';
    
    bootstrap(AppComponent, {
      providers: [
        provideToastr({
          timeOut: 2000,
          positionClass: 'toast-top-right',
        }),
      ],
    })
  11. Fix ExpressionChangedAfterItHasBeenCheckedError

    master

    If you encounter ExpressionChangedAfterItHasBeenCheckedError when opening a toast inside an Angular lifecycle hook (like ngOnInit), wrap the toast call in a setTimeout to move it to the next macrotask.

    ngOnInit() {
        setTimeout(() => this.toastr.success('sup'))
    }