Toasts provide feedback messages as notifications to the user.
Goal is to mimic the push notifications available both on mobile and desktop operating systems.

NgbToast component allows you to only render the corresponding markup. Use it in one of your templates, and you are done. It will render a toast.


Live example available here.

Nonetheless, with this inline technique, you must handle the toast's lifecycle yourself, i.e. it won't disappear automagically or in other words we don't remove the markup, nor destroy the component.

To make it disappear, you can listen to the (hide) output and remove/destroy/hide it yourself, and next section details how to do that in a real application environment.

Let's take the opportunity to demonstrate how to simply build a global toast management service.

TLDR; You don't feel reading these long explanations? Go to the live example here.

In order to create our global toast system, 3 simple steps need to be done:

  1. Create a global AppToastService to act as a global storage for toasts.
  2. Create a container component <app-toasts>, acting as the host in the application to display your toasts. You could use <ngb-toast> with an @for to read the list of toasts to display from the service.
  3. Finally, use this container component in your application.

1. Global toast service

Relying on Angular dependency injection to share some piece of logic application-wide is always a good and solid starting choice.

The service manages a collection of toasts. It also provides a public method to push a new toast to that same collection.

You could also create an interface to type your toast instead of using any[] here.

Additionally, a method to remove an existing toast from the collection is also implemented.

2. Toast container component

As stated previously, <ngb-toast> only generates a valid Bootstrap toast markup. You'll still have to position them properly on the screen.
Thus, as a suggestion, toasts could be rendered in the top right corner of the application, as a kind of overlay.

To achieve that, you could create a dedicated container component/element to render all toasts in a convenient way. For example, this container could be positionned using CSS property position: static.


Lastly, let's use this container. Common sense would suggest to put it somewhere quite high in your hierarchy of components. Your root component would be a good candidate.

You're done! Just inject and use your AppToastService anywhere you want to create a new toast. <app-toasts> will take care of displaying them.

Note the accessibility attributes aria-live="polite" & aria-atomic="true". They are mandatory in order to be compliant with screen readers technology. More information available on Bootstrap documentation.

Click here to see an example a bit more advanced of this how-to.