将最大 toastr 消息限制为两个

Limit max toastr messages to two

我想限制一次打开toasts的最大数量。 我正在使用 ngx-toastr 模块和 Angular5。 我已经像这样配置了全局设置:

ToastrModule.forRoot(
      { maxOpened: 2, 
        preventDuplicates: true,
        timeOut:2000,
        closeButton: true,
        progressBar:true,
        autoDismiss:true,
        newestOnTop:true}),

甚至在渲染之前清除了 toasts :

for(let i=0; i<10;i++){
  this.toastr.clear();
  this.toastr.info(''+i);
}

但是,仍然会同时显示许多吐司消息。

我创建了一个带有变通方法的 Stackblitz,一次只允许两次吐司,setTimeout 为 1 秒。

for(let i=0; i<10;i++){
  ((ind)=>{ setTimeout(()=> this.toastr.info(''+i),1000*ind)})(i)
}

https://stackblitz.com/edit/angular-phf1p6

您可以通过简单的 jQuery 选择来实现:

const MAX_TOASTS = 2;

toastr.subscribe(function(args) {
    if (args.state === 'visible')
    {
        var toasts = $("#toast-container > *:not([hidden])");
        if (toasts && toasts.length > MAX_TOASTS)
            toasts[0].hidden = true;
    }
});

jQuery 选择 $("#toast-container > *:not([hidden])") 选择 toast-container 的所有不具有属性 hidden 的子项。 Toastr,至少在使用 cdn 版本 2.1.4 时,将 hidden 属性添加到每个 is/will 被隐藏的 toast。

将 toast 的隐藏 属性 设置为 true 会隐藏它。