简体   繁体   English

在角度应用程序中全局使用ngx-toastr

[英]Using ngx-toastr globally in angular application

I am using the following toastr implementation in my Angular 7 app: https://www.npmjs.com/package/ngx-toastr 我在Angular 7应用程序中使用以下Toastr实现: https ://www.npmjs.com/package/ngx-toastr

I am trying to figure out on how can I make all the toasts append to the body, or other div element which will be in my root app component (I want to keep them displayed even in case where the component from which they are called will be destroyed). 我试图弄清楚如何使所有吐司附加到主体或其他div元素中,这些元素将出现在我的根应用程序组件中(即使在调用它们的组件会被摧毁)。

Is there any way to archive it? 有什么办法可以存档吗?

As the readme in your link already states, you need to provide your own ToastrContainer. 正如链接中的自述文件所述,您需要提供自己的ToastrContainer。

import { 
    ToastrModule, 
    ToastContainerModule // Add this one
} from 'ngx-toastr';


@NgModule({
  declarations: [AppComponent],
  imports: [
    //...
    ToastContainerModule // Add this one
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

And add a div to your root component (or anywhere you want the container to be) like this: 并将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');
  }
}

Declare the module on your root module (usually app.module.ts ) 在根模块上声明模块(通常是app.module.ts

import { ToastrModule } from 'ngx-toastr';

@NgModule({
    imports: [ ToastrModule.forRoot({ ...global options... }) ],
    ...
})

The toasts can the be called for anywhere (granted you've injected the service in your component) and should be shown where you have defined them to be shown (and that no element covers them). 可以在任何地方调用Toast(允许您将服务注入到组件中),并且应该在定义了Toast的位置显示Toast(并且没有元素覆盖它们)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM