Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger Toast on page load?

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?

like image 529
sml485 Avatar asked Jan 25 '19 13:01

sml485


Video Answer


1 Answers

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()
}
like image 190
jo_va Avatar answered Sep 17 '22 17:09

jo_va