ngx-toastr:如何在自定义Toast组件中获取当前Toast ID并关闭指定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

