Prevent duplicate toast display in EJ2 TypeScript Toast control
10 May 20235 minutes to read
You can prevent identical same toast displaying in a screen by the event function and terminate the toast displaying process by setting the cancel event property in the beforeOpen event.
The following sample demonstrates preventing duplicate title toast element displaying with custom code blocks.
import {Toast, ToastModel, ToastBeforeOpenArgs} from '@syncfusion/ej2-notifications';
import { enableRipple } from '@syncfusion/ej2-base';
enableRipple(true);
let toasts: ToastModel[] = [
{ title: 'Warning !', content: 'There was a problem with your network connection.' , isOpen: false},
{ title: 'Success !', content: 'Your message has been sent successfully.' , isOpen: false},
{ title: 'Error !', content: 'A problem has been occurred while submitting your data.' , isOpen: false },
];
let prevDuplicates: boolean = false;
let toastFlag: number = 0;
let toast: Toast = new Toast({
position: {
X: 'Center'
},
beforeOpen: onBeforeOpen,
close: onClose,
created: onCreate
});
toast.appendTo('#element');
++toastFlag;
document.getElementById('show_toast').onclick = () => {
toast.show(toasts[toastFlag]);
++toastFlag;
if (toastFlag === (toasts.length)) {
toastFlag = 0;
}
}
function onBeforeOpen(e: ToastBeforeOpenArgs): void {
if (preventDuplicate(e)) {
e.cancel = true;
}
}
function preventDuplicate(e: ToastBeforeOpenArgs): boolean {
for (let i: number = 0; i < toasts.length; i++) {
if (toasts[i].title === e.options.title && !toasts[i].isOpen) {
toasts[i].isOpen = true;
return false;
}
}
return true;
}
function onCreate(): void {
toast.show(toasts[toastFlag]);
++toastFlag;
}
function onClose(e: any): void {
for (let i: number = 0; i < toasts.length; i++) {
if (toasts[i].title === e.options.title) {
toasts[i].isOpen = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Essential JS 2 Toast</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Typescript Toolbar Controls" />
<meta name="author" content="Syncfusion" />
<link href="index.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/27.1.48/material.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
<div id='loader'>LOADING....</div>
<div id='container'>
<div class='row'> <button class="e-btn" id="show_toast"> Show Toast</button> </div>
<div id='element'></div>
<br/><br/>
<div id='result'></div>
<div id='templateToast' style="display: none;color:red"> System affected by virus !!! </div>
</div>
</body>
</html>