简体   繁体   中英

Using ngx-toastr globally in angular application

I am using the following toastr implementation in my Angular 7 app: https://www.npmjs.com/package/ngx-toastr

I am trying to figure out on how can I make all the toasts append to the body, or other div element which will be in my root app component (I want to keep them displayed even in case where the component from which they are called will be destroyed).

Is there any way to archive it?

As the readme in your link already states, you need to provide your own ToastrContainer.

import { 
    ToastrModule, 
    ToastContainerModule // Add this one
} from 'ngx-toastr';


@NgModule({
  declarations: [AppComponent],
  imports: [
    //...
    ToastContainerModule // Add this one
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

And add a div to your root component (or anywhere you want the container to be) like this:

@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');
  }
}

Declare the module on your root module (usually app.module.ts )

import { ToastrModule } from 'ngx-toastr';

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

The toasts can the be called for anywhere (granted you've injected the service in your component) and should be shown where you have defined them to be shown (and that no element covers them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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