簡體   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