javascript - 在 Angular 应用程序中全局使用 ngx-toastr
问题描述
我在我的 Angular 7 应用程序中使用以下 toastr 实现:https ://www.npmjs.com/package/ngx-toastr
我试图弄清楚如何使所有 toast 附加到主体或其他将在我的根应用程序组件中的 div 元素(即使在调用它们的组件将被销毁)。
有什么办法存档吗?
解决方案
正如链接中的自述文件已经指出的那样,您需要提供自己的 ToastrContainer。
import {
ToastrModule,
ToastContainerModule // Add this one
} from 'ngx-toastr';
@NgModule({
declarations: [AppComponent],
imports: [
//...
ToastContainerModule // Add this one
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
并将 div 添加到您的根组件(或您希望容器所在的任何位置),如下所示:
@Component({
selector: 'app-root',
template: `
<h1><a (click)="onClick()">Click</a></h1>
<div toastContainer></div> <!-- Add this line here, above should be your router -->
`
})
export class AppComponent implements OnInit {
// Get a reference to the directive
@ViewChild(ToastContainerDirective) toastContainer: ToastContainerDirective;
constructor(private toastrService: ToastrService) {}
ngOnInit() {
// Register the container
this.toastrService.overlayContainer = this.toastContainer;
}
onClick() {
this.toastrService.success('in div');
}
}
推荐阅读
- java - 如何通过合并在 IDEA 中运行 Sbt?
- python-3.x - 安装包时在 Jupyter notebook 中输入确认信息
- mysql - 概念混淆:在 GCP 中与 Wordpress 的云交互以及与 Spring 的 APP 交互
- c# - 为 Azure 服务总线会话处理器设置 WaitTimeOut
- javascript - 切换反应表单时如何关闭表单的自动完成?
- spring - 如何通过maven下载spring-web.jar的第三方依赖?
- spring-boot - 尝试运行 Spring Boot 应用程序时出现以下错误
- python - 仅从 PDF 文件中获取第一页
- php - 如何在 laravel 控制器中获取更改百分比值?
- amazon-web-services - 我需要快速解释 AWS Amplify Vue Storage amplify-s3-image-picker fileToKey