Igor Simic
6 years ago

Angular material display multiple toast




Following the Material Design guidelines, it is not possible to show more then one toast in Angular Material.  As explained here:
https://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-usage

But it is possible to show more than one toast one after another.

Let's asume we have to validate input form  and let's asume that several input fields contains invalid data. So the backend will send message for each invalid input field. In angular we can loop through these messages and show toast for each message

First we have to loop over each message and create array of md toast = toastList
var toastList = [];
var i =1;
angular.forEach(rejection.data.message, function(value, key){

                        toastList.push(
                          $mdToast.simple()
                              .textContent(value[0])
                              .theme('error-toast')
                              .position('top right')
                              .hideDelay(2500*i)
                        );    
                        i++;
                      });


And then we can use for loop  and execute every toastList with time delay

for(var i = 0; i < toastList.length; i++) {
                          (function(i){  
                              $timeout(function() {
                                  showCustomToast(i);
                              }, i * 3000);
                          })(i); // Pass in i here
                      }

                      function showCustomToast(i) {
                          $mdToast.show(toastList[i]).then(function(response) {
                            if ( response == 'ok' ) {
                              $mdToast.hide(toastList[i]); 
                            }
                          });
                      }


Notice that timedelay is 3000 and time to hide toast is 2500

More reading, how to show multiple snack-bar messages in Angular 2+ using Material deisign:
how to show multiple angular material SnackBar messages?