ngx-sonner

repository·master·Indexed 41 days ago

https://github.com/tutkli/ngx-sonner

An opinionated toast notification component for Angular based on the React 'sonner' implementation. It provides a customizable and accessible way to display transient messages, supporting various types including success, info, warning, error, and loading. Features include promise-based toasts, custom Angular component toasts, and deep integration with Tailwind CSS via an unstyled mode. Version 3.1.0 requires Angular ≥18.0.0 (v2.0.0+) or ≥17.3.0 (v1.0.0+).

Tokens
4.2K
Snippets
10
Records
17
Agent score
52%

What's inside ngx-sonner

  1. Quick start with ngx-sonner

    master

    To use ngx-sonner, follow these two steps:

    1. Add the <ngx-sonner-toaster /> component to your application (usually in your root component) to provide the rendering container.
    2. Import and use the toast() function from anywhere in your app to trigger notifications.

    Note: You must include NgxSonnerToaster in your component's imports array if using standalone components.

    import { toast, NgxSonnerToaster } from 'ngx-sonner';
    
    @Component({
      selector: 'app-root',
      imports: [NgxSonnerToaster],
      template: `
        <ngx-sonner-toaster />
        <button (click)="toast('My first toast')">Give me a toast</button>
    `
    })
    export class AppComponent {
      protected readonly toast = toast;
    }
  2. Style toasts with Tailwind CSS

    master

    To use Tailwind CSS effectively, use the unstyled property. This removes default styles and allows you to apply custom classes via the classes object.

    Global Styling (via Toaster)

    Use [toastOptions] on the <ngx-sonner-toaster /> to apply styles to all toasts.

    Individual Styling (via toast())

    Pass unstyled: true and a classes object directly to the toast() call.

    Available class keys:

    • toast: The main container
    • title: The toast title
    • description: The toast description
    • actionButton: The action button
    • cancelButton: The cancel button
    • closeButton: The close button
    • error, success, warning, info: Specific classes for different toast types (when using unstyled on the toaster).

    Note: You can also use standard style (inline CSS) and class (CSS class) properties.

    <!-- Global Tailwind Setup -->
    <ngx-sonner-toaster
      [toastOptions]="{
        unstyled: true,
        classes: {
          toast: 'bg-blue-400',
          title: 'text-red-400',
          description: 'text-red-400',
          actionButton: 'bg-zinc-400',
          cancelButton: 'bg-orange-400',
          closeButton: 'bg-lime-400'
        }
      }"
    />
    
    <!-- Individual Toast with Tailwind -->
    toast('Hello World', {
      unstyled: true,
      classes: {
        toast: 'bg-blue-400',
        title: 'text-red-400 text-2xl'
      }
    });
  3. Install ngx-sonner

    master

    Install ngx-sonner using your preferred package manager.

    Compatibility:

    • ngx-sonner v2.0.0+ requires Angular ≥18.0.0
    • ngx-sonner v1.0.0+ requires Angular ≥17.3.0
    npm i ngx-sonner
    # or
    yarn add ngx-sonner
    # or
    pnpm add ngx-sonner
    # or
    bun add ngx-sonner
  4. Use the NgxSonnerToaster component

    master

    The NgxSonnerToaster component (selector: ngx-sonner-toaster) is the required container that renders all toasts in your application. It manages toast positioning, themes, and global interactions like hotkeys. You should typically place this component at a high level in your Angular component tree (e.g., in app.component.html).

    <ngx-sonner-toaster></ngx-sonner-toaster>
  5. Manage toast lifecycle: Update, Dismiss, and Callbacks

    master

    Updating a toast

    To update an existing toast, call toast() again and pass the original id in the options object.

    Dismissing toasts

    • Specific toast: toast.dismiss(id) (the toast() function returns the ID).
    • All toasts: toast.dismiss() (call without an ID).

    Lifecycle Callbacks

    Pass these in the options object:

    • onDismiss: Fired when the toast is swiped away or the close button is clicked.
    • onAutoClose: Fired when the toast disappears automatically due to the duration timeout.
    // Update
    const toastId = toast('Sonner');
    toast.success('Updated!', { id: toastId });
    
    // Dismiss
    toast.dismiss(toastId);
    
    // Callbacks
    toast('Message', {
      onDismiss: (t) => console.log('Dismissed', t.id),
      onAutoClose: (t) => console.log('Auto-closed', t.id)
    });
  6. Create different types of toasts with toast()

    master

    The toast() function can be used to create various types of notifications. You can pass an options object as the second argument to customize them.

    Basic Types

    • Default: toast('Message') or toast('Message', { description: '...', icon: Component })
    • Success: toast.success('Message') (renders checkmark)
    • Info: toast.info('Message') (renders question mark)
    • Warning: toast.warning('Message') (renders warning icon)
    • Error: toast.error('Message') (renders error icon)
    • Loading: toast.loading('Message') (renders spinner)

    Interactive Toasts

    • Action: Adds a primary button. Use onClick to run a callback. You can prevent closing by calling event.preventDefault() in the callback.
    • Cancel: Adds a secondary button with an onClick callback.

    Promise-based Toasts

    toast.promise() handles loading, success, and error states automatically based on a Promise.

    Custom Components

    • Component Toast: Pass an Angular component directly as the first argument: toast(MyComponent).
    • Headless Toast: Use toast.custom(MyComponent) to render a completely unstyled component while keeping the toast functionality.
    // Success toast
    toast.success('Event has been created');
    
    // Action toast
    toast('My action toast', {
      action: {
        label: 'Action',
        onClick: () => console.log('Action!')
      }
    });
    
    // Promise toast
    toast.promise(promise, {
      loading: 'Loading...',
      success: (data) => `Added ${data.name}!`,
      error: 'Error'
    });
    
    // Headless custom component
    toast.custom(CustomComponent);
  7. Customize toast appearance with ToastOptions

    master

    Use ToastOptions (passed via the toastOptions property of the Toaster) to set default styling for all toasts. This is useful for maintaining a consistent look across your application.

    Available Properties

    • class: CSS class for the toast element.
    • descriptionClass: CSS class for the description element.
    • style: Inline CSS styles for the toast element.
    • cancelButtonStyle: Inline CSS styles for the cancel button.
    • actionButtonStyle: Inline CSS styles for the action button.
    • duration: Default duration in milliseconds.
    • unstyled: If true, removes default styling to allow full custom control.
    • classes: An object of ToastClassnames to target specific sub-elements.
  8. Configure the Toaster component

    master

    The ToasterProps interface defines the configuration for the <ngx-sonner> toaster component. These settings act as defaults for all toasts rendered within that toaster instance.

    Available Properties

    • theme: 'light' | 'dark' | 'system' (default: 'light')
    • position: Position (default: 'bottom-right')
    • invert: Boolean to show dark toasts in light mode and vice versa (default: false)
    • richColors: Boolean to make error and success states more colorful (default: false)
    • expand: Boolean to expand toasts by default (default: false)
    • visibleToasts: Number of toasts to show at once (default: 3)
    • closeButton: Adds a close button to all toasts, visible on hover (default: false)
    • duration: Default duration in milliseconds (default: 4000)
    • offset: Offset from screen edges (default: '32px')
    • gap: Gap between toasts in pixels (default: 14px)
    • hotkey: Array of strings for keyboard shortcuts to focus the toaster (default: ['⌥/alt + T'])
    • dir: Text directionality: 'ltr' | 'rtl' | 'auto' (default: 'ltr')
    • toastOptions: Configuration for individual toast styling and behavior (see ToastOptions)
    • loadingIcon: A TemplateRef to override the default loading icon.
  9. Configure the <ngx-sonner-toaster /> component

    master

    The <ngx-sonner-toaster /> component controls the global behavior and appearance of all toasts.

    Visual Configuration

    • theme: Set to 'light' (default) or 'dark'.
    • position: Placement on screen. Options: top-left, top-center, top-right, bottom-left, bottom-center, bottom-right. Default is bottom-right.
    • richColors: Enables colorful backgrounds for success, error, etc.
    • closeButton: Adds a close button that appears on hover.
    • expand: Boolean to expand toasts by default.
    • visibleToasts: Number of toasts to show at once (default is 3).
    • offset: Custom offset from screen edges (e.g., '80px').
    • duration: Global duration in ms. Use Number.POSITIVE_INFINITY for persistent toasts.

    Customization

    • hotKey: Array of event.code values to focus the toast area (e.g., ['KeyC']).
    • Custom Icons: Pass components inside the toaster using specific attributes:
      • <custom-icon loading-icon />
      • <custom-icon success-icon />
      • <custom-icon error-icon />
      • <custom-icon info-icon />
      • <custom-icon warning-icon />
    <ngx-sonner-toaster 
      theme="dark" 
      position="top-center" 
      [expand]="true" 
      [visibleToasts]="9" 
      richColors 
      closeButton 
      [duration]="10000"
    />
  10. Customize toast icons via NgxSonnerToaster content projection

    master

    You can override the default icons for different toast types by projecting content into the NgxSonnerToaster using specific attribute selectors. This allows you to use your own icon components or custom HTML.

    <ngx-sonner-toaster>
      <!-- Custom loading icon -->
      <div loading-icon>
        <my-custom-spinner />
      </div>
    
      <!-- Custom success icon -->
      <my-icon success-icon type="check" />
    
      <!-- Custom error icon -->
      <my-icon error-icon type="cross" />
    
      <!-- Custom warning icon -->
      <my-icon warning-icon type="alert" />
    
      <!-- Custom info icon -->
      <my-icon info-icon type="info" />
    </ngx-sonner-toaster>
  11. Configure shared toast styles with toastOptions

    master

    The toastOptions input allows you to pass a configuration object that applies to every toast rendered by the toaster. This is useful for maintaining visual consistency across all notifications.

    <ngx-sonner-toaster
      [toastOptions="{
        'actionButtonStyle': { 'borderRadius': '4px' },
        'cancelButtonStyle': { 'backgroundColor': 'red' },
        'class': 'my-custom-toast-class',
        'descriptionClass': 'my-description-class',
        'classes': { 'toast': 'extra-toast-class' },
        'duration': 5000,
        'unstyled': false
      }"
    >
    </ngx-sonner-toaster>