【问题标题】:Using ngx-toastr globally in angular application在 Angular 应用程序中全局使用 ngx-toastr
【发布时间】:2019-04-02 12:47:05
【问题描述】:

我在 Angular 7 应用程序中使用以下 toastr 实现:https://www.npmjs.com/package/ngx-toastr

我正在尝试弄清楚如何使所有 toast 附加到正文或其他将在我的根应用程序组件中的 div 元素(我希望保持它们显示,即使它们来自的组件被调用将被销毁)。

有没有办法存档?

【问题讨论】:

    标签: javascript angular typescript toastr


    【解决方案1】:

    正如链接中的自述文件所述,您需要提供自己的 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');
      }
    }
    

    【讨论】:

      【解决方案2】:

      在你的根模块上声明模块(通常是app.module.ts

      import { ToastrModule } from 'ngx-toastr';
      
      @NgModule({
          imports: [ ToastrModule.forRoot({ ...global options... }) ],
          ...
      })
      

      toast 可以在任何地方调用(假设您已经在组件中注入了服务),并且应该显示在您定义它们要显示的位置(并且没有元素覆盖它们)。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      相关资源
      最近更新 更多