Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ngx-french-toast

thiagopg84223Apache-2.019.0.0TypeScript support: included

ngx-french-toast logo

toast, angular, toastr, ngx-toastr, ngx-french-toast, ngx-french-toastr

readme

ngx-french-toast

ngx-french-toast logo

Check the Changelog for updates! 📌

You can test all features in ngx-french-toast playground app.


Features

  • Fully built in Angular, without any external dependencies. Oui, très indépendant!
  • Customizable toast appearance, including duration, colors, and positioning. Like a beret, you can style it to perfection!
  • Unique feature: Dynamically embed components within the toast for maximum flexibility and créativité. C'est magnifique!
  • Total control over toast visibility: infinite and pinned properties allow users to arrange toasts based on their importance and ensure critical messages stay in focus.

Compatibility Matrix

Angular ngx-french-toast
14^ - 15^ 1.3.x
16^ 1.4.x
17^ 2.x
18^ 18.x
19^ 19.x


Installation

To install ngx-french-toast, simply follow these étapes:

1. Run the following command to install the package via npm:

npm install ngx-french-toast

2. Import the FrenchToastModule in your Angular module:

Standard apps

import { FrenchToastModule, ToastPosition, ToastConfig } from 'ngx-french-toast';

// optional configuration object:
const config: ToastConfig = {
  colors: {
    danger: '#a20000', // Background color for the danger toast
    dangerText: '#ffffff', // Text color for the danger toast
    info: '#2d96f8', // Background color for the info toast
    infoText: '#ffffff', // Text color for the info toast
    success: '#2df877', // Background color for the success toast
    successText: '#ffffff', // Text color for the success toast
    warning: '#f8bb2d', // Background color for the warning toast
    warningText: '#ffffff', // Text color for the warning toast
    timebar: 'linear-gradient(45deg, #2b6bbf, #10425b)', // Or a single color -- background color for the time bar
    autoGradient: false // Controls whether the background will be an automatically generated gradient or not based on single input colors
  },
  defaultDuration: 100000,
  position: ToastPosition.TOP_RIGHT, // As elegant as the Eiffel Tower!
  limit: 3,
  font: {
    contentFontSize: '13px', // This will accept any CSS unit (rem, em, px etc.)
    titleFontSize: '15px', // Same here ;)
    family: 'Athiti' // Très élégant!
  }
};

@NgModule({
  imports: [
    // ...
    FrenchToastModule.forRoot(config)
  ]
  // ...
})
export class AppModule {}

Standalone apps

import { provideFrenchToast, ToastPosition } from 'ngx-french-toast';

bootstrapApplication(AppComponent, {
  providers: [
    provideFrenchToast({
      defaultDuration: 10000,
      position: ToastPosition.BOTTOM_RIGHT,
      limit: 2,
      font: {
        contentFontSize: '13px',
        titleFontSize: '15px',
        family: 'Athiti'
      }
    })
  ]
}).catch((err) => console.error(err));

3. Et voilà! You're ready to start using ngx-french-toast in your Angular application.


Usage

Here's a simple example demonstrating how to use ngx-french-toast:

import { Component } from '@angular/core';
import { ToastService } from 'ngx-french-toast';

@Component({
  selector: 'app-example',
  template: ` <button (click)="showToast()">Show Toast</button> `
})
export class ExampleComponent {
  constructor(private toastService: ToastService) {}

  showToast(): void {
    this.toastService.success({
      title: 'Knock, knock!',
      content: "Who's there? Eiffel. Eiffel who? Eiffel in love with you!" // Mon Dieu, l'amour!
    });
  }
}

Toast Types

ngx-french-toast provides 4 toast types. Each of them has its own method:

  • success(): Shows a success toast. C'est magnifique!
  • danger(): Shows a danger toast. Oh là là!
  • info(): Shows an info toast. Voilà!
  • warning(): Shows a warning toast. Attention!

You can use these methods of your ToastService instance to show toasts in your application. For example:

this.toastService.success({ title: 'Success', content: 'Your task has been completed with finesse!' });
this.toastService.danger({ title: 'Danger', content: 'Something went wrong! Oh là là!' });
this.toastService.info({ title: 'Info', content: 'Here are some important details for you.' });
this.toastService.warning({ title: 'Warning', content: 'Be cautious! Danger may be lurking nearby.' });

Toast Input Object

Each toast has the following customizable properties:

this.toastService.success({
  title: 'Toast Title',
  content: 'Lorem ipsum dolor sit amet.', // this will be ignored if you're embedding a component ;)
  _id: `success-toast--${this.id}`, // if you leave it blank, the ID will be automatically generated
  component: SomeComponent,
  duration: 10000,
  icon: '../assets/svg/sprite.svg#icon-success', // or a URL of a .png, for example
  infinite: true, // if infinite is true, the duration will be ignored
  pinned: true, // when set to true, this toast will remain fixed in its position even if new toasts are added, unless the next toast is also pinned
  context: {
    // this will be available within SomeComponent!
    name: 'Jean Pierre',
    email: 'jetaime@lesbleus.fr'
  }
});

Embedding Components Dynamically

To embed components dynamically just call any method from your instance of ToastService and pass an object with the component and title properties. For example:

this.toastService.success({
  component: ExampleComponent,
  title: 'Oui, mon ami!',
  context: {
    name: 'Jean Pierre',
    email: 'jetaime@lesbleus.fr'
  } // the content and type of context is up to you!
});

Grabbing the context object from the embedded component

To have access to the context object from within your dynamically embedded component, you just have to create a context variable in your embedded component to receive the content you declared when calling the ToastService:

context: { name: string, email: string }; // the type is up to you :)

Programmatically closing the parent toast from the embedded component

To close the parent toast from the embedded component, users should follow these steps:

⚠️ Attention! This is a breaking change.

1. In the embedded component (e.g., ExampleComponent), define an EventEmitter named destroyToast as an @Output() property:

- @Output() destroyToast: EventEmitter<boolean> = new EventEmitter<boolean>(false);
  1. In the embedded component (e.g., ExampleComponent), inject an instance of ToastService and the parent component (ToastComponent) as dependencies:
import { ToastComponent, ToastService } from 'ngx-french-toast';

constructor(private toastService: ToastService, private toast: ToastComponent) {}
  1. Call the destroyToast method from ToastService, passing the parent component as a parameter:
closeToast(): void {
  this.toastService.destroyToast(this.toast);
}

To summarize, here's an example for the whole section:

import { Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <p>My email: {{ context.email }}</p>
    <button (click)="rate(5)">Five stars!</button>;
  `
})
export class ExampleComponent {
  context: { name: string; email: string };

  constructor(
    private toastService: ToastService,
    private toast: ToastComponent
  ) {}

  rate(rate: number): void {
    this.someApi.rate(rate).subscribe({
      next: () => {
        this.toastService.destroyToast(this.toast);
      }
    });
  }
}

Passing the parent component to the destroyToast method allows ToastService to find the ToastComponent within visible toasts and close it. Très beau!


Using Icons

You can customize the toast appearance by adding icons. Simply pass an icon property inside the config object when calling the toast service. The icon property accepts a string that can link directly to images or SVG sprite files. Here are a few examples:

Using an SVG from a sprite:

this.toastService.success({ title: 'Success', icon: '../assets/svg/sprite.svg#icon-success' }); // Comme un baguette of success!

Using an image:

this.toastService.success({ title: 'Success', icon: '../assets/imgs/success.png' }); // C'est magnifique!

Note: Make sure to provide the correct path to the image or SVG file. Parfait!


Clearing Toasts Programmatically

Sometimes, you might need to remove all toasts from the screen at once. To do this programmatically, simply call the clearAllToasts() method from your ToastService instance:

this.toastService.clearAllToasts();

This can be particularly useful when, for instance, you want to reset the toast notifications or clear the screen after a certain action has been taken.


Contributions

Contributions to ngx-french-toast are welcome! If you find a bug, have a feature request, or want to contribute code improvements, please submit an issue, or fork it, or just let me know and we'll figure it out 😊


Contact

If you have any questions, suggestions, or feedback, you can reach out to me via thiago2k9@gmail.com or find me on LinkedIn. Don't hesitate to say "Bonjour!" and share your thoughts. Let's connect and make the ngx-french-toast community even stronger! 💪🥐

Made with ❤️ (and lots of croissants) for Angular Angular Logo.

Merci beaucoup for using ngx-french-toast! I hope it brings a touch of créativité to your Angular applications. Bon appétit! 🍞

changelog

ngx-french-toast Changelog

All notable changes to the ngx-french-toast library will be documented in this file.


19.0.0 (2025-06-13)

  • Angular Update: Following our update policy, we implemented support for and migrated to the latest Angular 19. Consequently, this release is exclusively compatible with Angular 19 projects.

  • Visual Overhaul: We've teamed up with a UX/UI designer to deliver a modernized, cleaner, and more consistent look for the toast component. This update enhances visual clarity, improves accessibility, and aligns the styling with contemporary UI standards — making your toasts feel right at home in any Angular 19 app.


18.0.1 (2024-10-20)

Fixed

  • Window object: Previously, on toast.component.ts, the window object was being used to reference a timeout. For some reason, in the newer versions of Angular (18.2.x) the object was not being found. This version will fix that.

18.0.0 (2024-05-16)

⚠️ BREAKING CHANGES! ⚠️

  • Angular Update: Following our update policy, we implemented support for and migrated to the latest Angular 18. Consequently, this release is exclusively compatible with Angular 18 projects. Also, to simplify the process for developers to find the correct version of ngx-french-toast for their Angular applications, we've aligned our version number with the Angular version. This means we've jumped from 2.1.1 to 18.0.0.

Ensure that your Angular applications are upgraded to version 18 to take advantage of its enhanced features and optimizations.

  • Closing parent Toast when using embedded components: Previously, developers had to create an EventEmitter and emit a boolean to close the parent component. To streamline this process and adopt a cleaner approach, a new method has been introduced. Now, to close the parent toast from an embedded component, follow these steps:

    1. In the embedded component (e.g., ExampleComponent), inject an instance of ToastService and the parent component (ToastComponent) as dependencies:
    import { ToastComponent, ToastService } from 'ngx-french-toast';
    
    constructor(private toastService: ToastService, private toast: ToastComponent) {}
    1. Call the destroyToast method from ToastService, passing the parent component as a parameter:
    closeToast(): void {
      this.toastService.destroyToast(this.toast);
    }

    Additionally, a new _uId property has been introduced to the interface ToastModel. This property is automatically generated and should not be manually assigned. It allows ToastService to accurately identify and close individual toast components.


2.1.1 (2024-02-10)

Fixed

  • Close Icon Color: Previously, although changing text colors for each type of toast was supported, the text color setting did not apply to the close (X) icon. This issue has been addressed by updating the close icon styles in toast.component.scss:

    .icon::before, .icon::after {
      content: '';
      position: absolute;
      width: 15px;
      height: 2px;
    - background-color: #fff;
    + background-color: var(--text-color);
      transform-origin: center;
    }

2.1.0 (2023-12-15)

Added

  • Colors Configuration: Introducing a new feature that allows users to customize toast colors. Now, you have full control over the background and text colors for different types of toasts. See the updated configuration options in the documentation to get started. Don't forget that these are optional and the library provides fallback for every configuration.
import { FrenchToastModule, ToastPosition, ToastConfig } from "ngx-french-toast";

const config: ToastConfig = {
  colors: {
    danger: "#a20000", // Background color for the danger toast
    dangerText: "#ffffff", // Text color for the danger toast
    info: "#2d96f8", // Background color for the info toast
    infoText: "#ffffff", // Text color for the info toast
    success: "#2df877", // Background color for the success toast
    successText: "#ffffff", // Text color for the success toast
    warning: "#f8bb2d", // Background color for the warning toast
    warningText: "#ffffff", // Text color for the warning toast
    timebar: "linear-gradient(45deg, #2b6bbf, #10425b)", // Background color for the time bar
    autoGradient: false, // Controls whether the background will be an automatically generated gradient or not based on single input colors
  },
};

2.0.0 (2023-12-15)

⚠️ BREAKING CHANGE! ⚠️

  • Angular Update: Implemented support for and migrated to the latest Angular 17. Consequently, this release is exclusively compatible with Angular 17 projects.

Ensure that your Angular applications are upgraded to version 17 to take advantage of its enhanced features and optimizations.


1.4.0 (2023-12-10)

⚠️ BREAKING CHANGES! ⚠️

  • Angular/CDK Integration: The toast rendering mechanism has been revamped using Angular Component Development Kit (CDK) Portals. Users no longer need to add the <french-toast></french-toast> selector to their templates. This change simplifies integration and provides a more streamlined user experience.
  • Angular Update: Migrated ngx-french-toast to Angular 16. Ensure that your Angular applications are also updated to the latest version for seamless integration.

Added

  • Standalone Application Support: ngx-french-toast now can be initialized without the need for a module:
bootstrapApplication(AppComponent, {
  providers: [
    provideFrenchToast({
      defaultDuration: 10000,
      position: ToastPosition.BOTTOM_RIGHT,
      limit: 2,
      font: {
        contentFontSize: "13px",
        titleFontSize: "15px",
        family: "Athiti",
      },
    }),
  ],
}).catch((err) => console.error(err));

Improved

  • ToastComponent and ToastsComponent are now Standalone.

1.3.0 (2023-11-03)

Added

  • Introducing a font object in the ToastConfig interface, offering enhanced customization of font attributes for your toasts. Define custom font family, title font size, and content font size.
@NgModule({
  ...
  imports: [
    FrenchToastModule.forRoot({
      font: {
        contentFontSize: '13px',
        titleFontSize: '15px',
        family: 'Athiti'
      }
    })
  ],
  ...
})

1.2.1 (2023-08-27)

Improved

  • Revised the OnDestroy approach: destroy$ is now a Subject of type void instead of boolean;
  • Revised the approach for handling clicks on dynamically embedded components. To enhance user experience (and to make things easier for developers), Toasts containing embedded components will now feature a dedicated button for convenient closure. This change ensures that clicking on the Toast body will no longer trigger its automatic dismissal. Therefore, manually preventing the click event from propagating in your embedded component is no longer necessary:
  rate(
    rate: number,
    // event: Event (no longer necessary!)
  ): void {
    // event.stopPropagation(); (no longer necessary!)
    this.someApi.rate(rate)
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => { this.destroyToast.emit(true); })
  }

1.2.0 (2023-08-18)

Added

  • Introduced enhanced component embedding. You can now seamlessly pass context data to dynamically embedded components within toasts:

    this.toastService.success({
      title: 'Dynamic Components!',
      component: MyLovelyComponent
      context: {
        name: 'Jean Pierre',
        email: 'jetaime@lesbleus.fr'
      }
    });
    
    @Component(...)
    export class MyLovelyComponent {
      @Input() context!: {
        name: string,
        email: string
      };
    }

1.1.0 (2023-08-12)

Added

  • Introduced the pinned property to ToastInputModel, enabling users to control whether a Toast should remain fixed on the screen. This feature offers complete autonomy over toast behavior. Combining pinned with fixed ensures the toast remains perpetually visible, unaffected by other toasts (unless other pinned toasts are subsequently added).

    this.toastService.success({
      title: "I shall remain!",
      content: "Other toasts shall flock around me :P",
      pinned: true,
    });

1.0.0 (2023-08-02)

Added

  • Added the property infinite to ToastInputModel to control whether or not the Toast expires.

    this.toastService.success({
      title: "I will not go away!",
      content: "I will not expire and won't have a countdown :)",
      infinite: true,
    });

Enhanced

  • Improved the unsubscribe strategy across the project using takeUntil operator.

0.9.91 (2023-07-18)

Updated

  • Updated Angular version to 15.2.9.

Fixed

  • Fixed peerDependencies to allow users to use the library in Angular 16 applications as well.

Enhanced

  • Implemented a playground in test-app so that users can take a better look at how easy it is to implement the library :)

0.9.9 (2023-07-01)

Fixed

  • Fixed peerDependencies to allow users to use the library in Angular 15 applications as well.

0.9.8 (2023-06-26)

Added

  • Implemented functionality to allow users to change the limit of toasts in the screen
    • When importing FrenchToastModule you now can pass a value for the ToastConfig.limit property:
      @NgModule({
      ...
      imports: [
        FrenchToastModule.forRoot({
          defaultDuration: 10000,
          position: ToastPosition.BOTTOM_RIGHT,
          colors: {},
          limit: 3
        })
      ],
      ...
      })

0.9.7 (2023-06-17)

Added

  • Implemented functionality to allow users to change the time-bar color
    • When importing FrenchToastModule you now can pass a value for the ToastConfig.colors.timebar property:
      @NgModule({
      ...
      imports: [
        FrenchToastModule.forRoot({
          defaultDuration: 10000,
          position: ToastPosition.BOTTOM_RIGHT,
          colors: {
            timebar: '#ffaa00',
            // or even a gradient:
            // timebar: 'linear-gradient(45deg, #ffaa00, #ff6c00)' // C'est si beau!
          }
        })
      ],
      ...
      })