首页 > 解决方案 > 在 Angular 应用程序中全局使用 ngx-toastr

问题描述

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

我试图弄清楚如何使所有 toast 附加到主体或其他将在我的根应用程序组件中的 div 元素(即使在调用它们的组件将被销毁)。

有什么办法存档吗?

标签: javascriptangulartypescripttoastr

解决方案


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

推荐阅读