You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ngx-toastr:如何在自定义Toast组件中获取当前Toast ID并关闭指定Toast

How to Get Toast ID in Custom Toast Component to Close Specific Toast

Hey there! I see you're trying to close a specific Toast when clicking its internal button—let's sort this out by grabbing the right Toast ID.

Looking at your existing code, you're already using ToastPackage which is actually the key here! Most toast libraries (like ngx-toastr, which it looks like you're working with) include the unique Toast ID directly in the ToastPackage instance injected into your custom component.

Here's how to adjust your code:

Replace the placeholder toastID with this.toastPackage.toastId—this is the unique identifier tied to the current Toast instance:

action(btn: IToastButton) { 
  event.stopPropagation(); 
  this.toastPackage.triggerAction(btn); 
  // Use the toastId from the injected ToastPackage
  this.toastrService.remove(this.toastPackage.toastId); 
  return false; 
}

Why this works:

Every Toast instance gets its own ToastPackage object, which holds metadata specific to that exact Toast—including the unique toastId. By accessing this.toastPackage.toastId, you're targeting precisely the Toast whose button was clicked, so you won't accidentally close any other active Toasts.

Just double-check that your custom Toast component has properly injected ToastPackage (which it seems like you do, since you're already using this.toastPackage) and this should work smoothly!

内容的提问来源于stack exchange,提问作者sairaj naik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:12:37