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

时间:2019-04-02 12:47:06

标签: javascript angular typescript toastr

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

我试图弄清楚如何使所有吐司附加到主体或其他div元素中,这些元素将出现在我的根应用程序组件中(即使它们来自哪个组件,我也希望它们保持显示状态被称为将被销毁。)

有什么办法可以存档吗?

2 个答案:

答案 0 :(得分: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');
  }
}

答案 1 :(得分:0)

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

import { ToastrModule } from 'ngx-toastr';

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

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