Ionic 3 - undefined variable in Ionic3 page


#1

Hello,
I have 2 questions regarding ionic 3.

  1. In my ionic3 page I declare a variable called ‘test’ whict cannot be access in actionOnClick function . Does anyone know way? What should I do so that ‘test’ in accessible anywere in FUNCTION_TEST function?

  2. Is there a way to make possible the variables exchange between HomePage and FUNCTION_TEST?

Bellow is my ionic3 code.

import { Component,ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Content} from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content) content:Content;
  test:string="text 1";

  constructor(public navCtrl: NavController) {

  }

  ionViewDidEnter(){
     this.FUNCTION_TEST();
  }

  FUNCTION_TEST(){
     var x=1;

     function actionOnClick(){
         alert("text="+this.test);  
     }

  }
}

Is it possible that my problem have to do with javascript and not with ionic?

Thanks a lot for your help!


#2

You can’t use the alert(); option in ionic unless you installed the jQuery library.

Use this code instead of your provided code:

import { Component, ViewChild } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  text;

  constructor(public alertCtrl: AlertController, public navCtrl: NavController) {
    this.test();
  }

  test(){
     this.text = 'text 1';

     let alert = this.alertCtrl.create({
      'title': 'Test alert',
      'message': this.text
     });

     alert.present();
  }
}

#3

Maybe you are not calling the second function which is :

See the below code for nested function in typescript:

class A
{
   public func1()
   {
      let sample = () => 
      {
         this.func2();
      }
   }
   public func2()
   {

   }
 }

#4

Thank you. Your suggestion helped me finding the solution. In order to work I wrote

FUNCTION_TEST(){
 var x=1;

 let actionOnClick = () => {
     alert("text="+this.test);  
 }

 }