A toast is a type of notification that commonly used in modern applications. You can use it to display the system message, or you can use it to provide feedback about an operation. The toast notification appears on top of the app's content. It can be dismissed by the app to resume user interaction with the app.
The toast controller is a component, which is used to create a toast component. The toast controller uses two methods to create toast notification. These methods are:
It is used to create a toast overlay. All of the toast options should be passed inside the create method. The message property used to display the message. If you want to display the close button on the toast, set the showCloseButton option to true.
The following example uses the toast controller method create() to show the toast notification. In the HTML file, the button component calls the openToast() function to display the toast notification. The logic of the function is created in the ts file of the application. The openToast() function also contains the property's message and duration. The message property will display the notification message, and duration property dismissed the notification after a specified time.
When you execute the app, it will give the following output.
Now, click on the Show Toast button, you will get the notification message. The notification message dismisses after five seconds.
The toast notification can be dismissed automatically after a specific amount of time by setting the number of milliseconds to display in the duration of the toast option. If you set the "showCloseButton" to true, the close button will dismiss the toast. If you want to dismiss the toast after creation, call the dismiss() method.
In this file, we are going to use the dismiss method. The dismiss method disappears the toast notification as soon as you click on the hide button.
When you execute the above Ionic app, it will give the following output. Now, click on the Show Toast button, the notification message appears at the bottom. Click the hide button, the toast notification will be disappeared, and the corresponding message displayed in the console.
You can position the toast notification at the top, bottom, middle of the viewport. The value of the position attributes can be set inside the create method. The position values are top, bottom, and middle. By default, the position of the toast notification displays at the bottom of the viewport.
In the following example, we are going to see the use of position properties. Here, the position of the toast notification is set in the middle.
When you run the above code snippets, you will get the output. Next, click on the button, you will get the following screen. Here, you can see the toast notification displays in the middle.