Global Toast. Cannot read property 'nativeElement' of null

In my app I am trying to implement a global toast that displays when no internet is detected and is dismissed when connection is brought back no matter where you are in the app. However I get an error after the second time the toast pops back up after losing connection: cannot read property ‘nativeElement’ of null. Also I am wondering if this is the best way to do this, heres the code:

        ngOnInit() {
          this.networkToast = this.toastCtrl.create({
              message: 'No Internet Connection',
              position: 'bottom'
          });
    
          // watch network for a disconnect
          let disconnectSubscription = Network.onDisconnect();
          disconnectSubscription.subscribe(() => {
              this.networkToast.present()
          });
    
          // watch network for a connection
          let connectSubscription = Network.onConnect();
          connectSubscription.subscribe(() => {
              this.networkToast.dismiss();
          });
        } 
        

This code is in my app.ts or my root component, so no matter where you are in the app the listeners will always trigger when the network is connected or disconnected but the toast seems to throw the error. I tried adding timeouts right before presenting the toast along with onDidDissmissAll method. Any have this issue? Thanks in advance.

I have had this issue too, I think its because once the toast is dismissed. It doesn’t exist anymore, and the ‘this’ pointer points to an element that is not a part of the DOM anymore.

Using let instead of a class property which you reference with ‘this’ fixed this issue for me

So instead of

this.networkToast = this.toastCtrl.create({
     message: 'No Internet Connection',
     position: 'bottom'
 });

You actually do something like

let networkToast = this.toastCtrl.create({
   message: 'No Internet Connection',
   position: 'bottom'
}

You can create a toast and re assign it inside the onDisconnect callback

 private networkStatus() {
    let toast = this.showToast('You are curretly offline');
    this.network.onDisconnect().subscribe(() => {
      toast = this.showToast('You are curretly offline');
      console.log('disconnected');
      toast.present();
    });
    this.network.onConnect().subscribe(() => {
      setTimeout(() => {
        console.log('reconnected');
        toast.dismiss();
      }, 3000);
    });
  }