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?
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With