Ionic 4 | Adding Toasts in Ionic 4 Application using UI Components without Plugins

In most of the applications these days whether they are mobile or web-based show information notifications in the form of toasts. Toasts are used in application to notify users are operational feedbacks like an error message, success alert or update information notification.

In the Ionic application as well we have beautiful Toast UI components which can be used without any plugin. In this post, we will add Ionic Toasts in few steps and also discuss some of the basic methods like Creating, Positioning and Dismiss toasts.

There are also some options provided to modify user behavior and How to customize Ionic Toasts by adding a custom CSS class.

Let’s do it

Create Ionic 4 Application

First, here we are creating a new Ionic application using latest Ionic CLI version.

Next, we will add a method to show an Ionic toast. Open home.page.ts file then Import Toast Module and also add in the constructor

To show toast we will call the create method that returns promise

In the method above we have used some options available using which we can modify toast behavior, look and feel.

duration: Time in milliseconds to auto hide toast.

message: Text to show in in toast notification

showCloseButton: Boolean value to show/hide a button to close toast.

closeButtonText: Add customized text for close button.

cssClass: Add a custom class to toast.

position: Position can be changed to “top”, “middle” or “bottom”

You can check more options available here

How to show toast only once and not stack?

In common behavior Ionic toasts are stacked on previous one if we call present method again and again. For prevent this and hide previous toast before next comes just modify above code

here I am calling manageToast method on finally callback which will be called in both cases if there is any open toast or not. Let me know if you have better workaround for now 😛

How to customize UI toast styling using custom class and CSS custom properties?

We can easily modify Toast by adding a custom class in option property

cssClass: “my-custom-class”

Add below CSS code in global.scss file as toast container is appended outside component page.

you can check these CSS custom properties available here

 

Leave a Reply

avatar
  Subscribe  
Notify of