Thursday, 23 March 2017

How to Implement Toast in Ionic 2 with ToastController

A Toast is a short notification that is commonly used on modern applications. it is commonly used to provide feedback/ indicate user  about a particular task's status or to simply display a short message.Toast can be displayed either on the top of the screen or on the bottom area.

Ionic 2 makes it easy to implement toast on your app's. follow the below steps to implement toast in your ionic 2 app.

Import ToastController from ionic-angular to the component in which you are implementing toast.




import { ToastController } from 'ionic-angular';


Now inject ToastController in your component’s class constructor




constructor(private myToastCtrl: ToastController) {}


Now that we have injected toastcontroller in to our components constructor, we can use myToastCtrl to display toast in our app. copy and paste the below code on to your component class, to display a 3 second toast on your ionic 2 app.




presentMyToast() {

let toast = this.myToastCtrl.create({
message: 'Toast Displayed Successfully! yay!!',
duration: 3000,
position: 'top'
});

toast.onDidDismiss(() => {
console.log('toast Dismissed');
});

toast.present();
}


How the Above Code Works?


when ever presentMyToast() method is called, it create's a toast with "this.myToastCtrl.create()", given it the options message, duration, position as above.

"toast.present()" display's the toast on our application where as "toast.onDidDismiss()" is called when ever the toast is dismissed.

ToastController Advanced Options


message: The message that is shown on the toast, takes string as type.

duration: Milliseconds to wait before hiding the current toast. takes number as type.

position: Where the toast should appear on the screen. default type is string.

cssClass: To add custom styling to toast. default type is string.

showCloseButton: used to show close button on toast. defaults to false,

closeButtonText: Text to display in the close button, if "showCloseButton" option is set to true .

dismissOnPageChange: Whether to close the toast when navigating to a other page/screen.

0 comments:

Post a Comment