Show toastrs after the previous toastr is dismised

166 Views Asked by At

I have multiple messages. I want to show next toastr after the toastr is dismissed. I write the following codes:

this.messages.forEach(msg=>{
  this.toastr.info(msg.Text, 'Title', 
  {
    positionClass: 'toast-top-right',
    closeButton: true,
    disableTimeOut: true,
  });
});

But all of my messages are appeared at the same time.

Here is what I want to:

Only one message appear on the screen, and then after dismissing the message, the next message will be shown.

2

There are 2 best solutions below

0
On BEST ANSWER

To display toastr messages sequentially, I write the following method:

displayNextMessage(messages, index) {
  if (messages !== undefined && index < messages.length) {
    const msg = messages[index];
    
    this.toastr.info(msg.Text, 'Title', {
      positionClass: 'toast-top-right',
      closeButton: true,
      disableTimeOut: true,
    }).onHidden.pipe(take(1))
    .subscribe(() => this.displayNextMessage(messages, index + 1));
  }
}

To call the method:

displayNextMessage(messages, 0);
0
On

To show toastrs one after another, waiting for each toastr to be dismissed before showing the next one, you can use a recursive approach. Here's how you can achieve this:

// Assuming you have an array of messages
this.messages = [
  { Text: 'Message 1' },
  { Text: 'Message 2' },
];

// Function to display toastr messages recursively
displayToastr(index: number) {
  if (index < this.messages.length) {
    const msg = this.messages[index];
    this.toastr.info(msg.Text, 'Title', {
      positionClass: 'toast-top-center',
      closeButton: true,
      disableTimeOut: true,
      onHidden: () => {
        this.displayToastr(index + 1); // Show the next toastr after the current one is dismissed
      }
    });
  }
}

// Call the function to start displaying toasters
this.displayToastr(0);

This code snippet defines a recursive function displayToastr that takes an index as a parameter. It displays the toastr at the given index and, when that toastr is dismissed (hidden), it calls itself with the next index to show the next toastr in the array.

With this approach, only one toastr will be displayed at a time, and the next one will be shown only after the previous one is dismissed.