Understanding Alerts

Hi, I’m a noob here and I’m getting a stange error with alerts. I search for the error on the forums but I couldn’t find anything similiar. Maybe that way I’m using alerts is not the intended way, if thats the case I’m sorry for not understanding it.

They way I’m using alerts is the following:

import { NavController, AlertController } from 'ionic-angular';
@Component({
	selector:"page-home",
	templateUrl: 'home.html'
})

export class HomePage {

        private alert;

        constructor(public navCtrl: NavController, public alertCtrl: AlertController) {
                this.alert = this.alertCtrl.create({
			title: "Test",
			subTitle: "Test",
			buttons: ["OK"]
		});
	}

        showAlert(){
                this.alert.present();
        }

}

and I just have an html page with a button connected with showAlert.

When I press the button it work perfect, the problem comes when I press the button again after dismissing the alert, it just errors:

console.error: EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of null 
console.error: ORIGINAL STACKTRACE: 
console.error: Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of null at s 
            (http://192.168.1.109:8100/build/polyfills.js:3:8568) at http://192.168.1.109:8100/build/polyfills.js:3:8940 
            at t.invokeTask (http://192.168.1.109:8100/build/polyfills.js:3:14051) at Object.onInvokeTask 
            (http://192.168.1.109:8100/build/main.js:29664:37) at t.invokeTask 
            (http://192.168.1.109:8100/build/polyfills.js:3:13987) at e.runTask 
            (http://192.168.1.109:8100/build/polyfills.js:3:11411) at i 
            (http://192.168.1.109:8100/build/polyfills.js:3:8028) 

Is it that instances of AlertController aren’t meant to be presented more than once? or is this a bug?
Thanks in advance.

ionic info:

Cordova CLI: 6.4.0 
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: macOS Sierra
Node Version: v7.3.0
Xcode version: Xcode 8.2.1 Build version 8C1002
1 Like

Technically speaking, it’s instances of components created by AlertController.create, but yes, your instinct is correct. Do not attempt to reuse them; create a new one each time. Same goes for LoadingController, ToastController, etc.

1 Like

Oh thanks! I wished that was written somewhere.

1 Like