Search code examples
angularangular5angular-router

ng2-toastr not working when navigated to different page


I am using ng2-toastr to display notification messages. I works fine when i am in the same page but when i navigate to another route it will not appear on the new page

I set the route for the ViewContainerRef inside the main component of my app

app.component.ts

import { Component, ViewContainerRef } from '@angular/core';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  public viewContainerRef: ViewContainerRef;

  public constructor(public toastr: ToastsManager, viewContainerRef: ViewContainerRef) {
    this.toastr.setRootViewContainerRef(viewContainerRef);
  }
}

sub component.ts

import { ToastsManager } from 'ng2-toastr/ng2-toastr';

 constructor(
    public toastr: ToastsManager,
    vcr: ViewContainerRef,
    private tripService: TripService) {
      this.toastr.setRootViewContainerRef(vcr);
 }

...
login() {
this.toastr.success('User Create Successfully !!..');
        this.router.navigate(['/login']);
}

Solution

  • Try this,

    app.component.ts

    import { Component, ViewContainerRef } from '@angular/core';
    import { ToastsManager } from 'ng2-toastr';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
    
      public viewContainerRef: ViewContainerRef;
    
      public constructor(public toastr: ToastsManager, viewContainerRef: ViewContainerRef) {
        this.viewContainerRef = viewContainerRef;
    
        this.toastr.setRootViewContainerRef(viewContainerRef);
      }
    }
    

    sub.component.ts

    import { ToastsManager } from 'ng2-toastr/ng2-toastr';
    
     constructor(
        public toastr: ToastsManager,
        private tripService: TripService) {
     }
    
    ...
    login() {
    this.toastr.success('User Create Successfully !!..');
            this.router.navigate(['/login']);
    }
    

    I hope this helps you. You don't need to import ViewContainerRef in each and every component.