[FIXED] How to trigger Toast on page load?

Issue

I am trying to use a <p-toast> in my landing page to display notification messages when users login.

<p-toast position="top-center" key="tc"></p-toast>

The messages are then declared in my components.

ngOnInit() {

    // add toasts
    this.messageService.addAll([
      {key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 1'},
      {key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 2'}
    ]);

    // do other stuff

}

This doesn’t work. To confirm that it is not a problem with my toast or messages, I placed the messages inside an onClick() event on the page and manually triggered it, which does work.

How do I get the Toasts to trigger on page load instead?

Solution

You have to send the messages once the view is initialized.

However, by triggering the messages in the ngAfterViewInit hook, you might get an ExpressionChangedAfterItHasBeenCheckedError.

Here are solutions to avoid this error:

First solution is using a setTimeout call to send the messages once everything is initialized.

Here is a simple Stackblitz example

ngAfterViewInit() {
    setTimeout(() => {
        this.messageService.addAll([
            {key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 1'},
            {key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 2'}
        ]);
    })
}

Another solution is to force change detection using the ChangeDetectorRef (see this article):

constructor(private messageService: MessageService, private cd: ChangeDetectorRef) { }

ngAfterViewInit() {
    this.messageService.addAll([
        {key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 1'},
        {key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 2'}
    ]);
    this.cd.detectChanges()
}

Answered By – jo_va

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published