在角度应用中全局使用 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');
}
}

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

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

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

最新更新