繁体   English   中英

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

[英]Using ngx-toastr globally in angular application

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

我试图弄清楚如何使所有吐司附加到主体或其他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');
  }
}

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

import { ToastrModule } from 'ngx-toastr';

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

可以在任何地方调用Toast(允许您将服务注入到组件中),并且应该在定义了Toast的位置显示Toast(并且没有元素覆盖它们)。

暂无
暂无

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

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