How to add dynamic template in EJ2 TypeScript Toast

04 Sep 20263 minutes to read

Toast supports changing templates dynamically when displaying in multiple toasts. The Toast properties can be changed while calling the show method.

import {Toast, ToastClickEventArgs } from '@syncfusion/ej2-notifications';
import { enableRipple } from '@syncfusion/ej2-base';

enableRipple(true);

let toast: Toast = new Toast({
    position: { X: 'Right', Y: 'Bottom' }
    click: onClick
});

let toastFlag: number = 0;
let toasts = [ { template: '2 Mail has received'},{ template: 'User Guest Logged in'},{ template: 'Logging in as Guest'},{ template: 'Ticket has reserved '},{ template: '#templateToast' }];

toast.appendTo('#element');
toast.show(toasts[toastFlag]);
++toastFlag;

document.getElementById('show_toast').onclick = () => {
  toast.show(toasts[toastFlag]);
  ++toastFlag;
  if (toastFlag === (toasts.length)) {
      toastFlag = 0;
  }
}

function onClick(e: ToastClickEventArgs ): void {
  e.clickToClose = true;
}
<!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/35.1.37/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>
</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>