[Solved] Increase variable


#1

Hi guys,
currently I am feeling a bit dumb because of my problem: I want to increase the value of a variable everytime I click a button.

.ts:

countup(){
		let count:number=0;
		count++;
		console.log(JSON.stringify(count));
	}

.html:

<button ion-button(click)="countup()">Count Up</button>

Now, everytime I click the button the result is console.log: 1, but I want it to be console.log: 1, than console.log: 2, than console.log: 3 and so on.

I am thankfully for help!

Greetings,

Robert


#2

You reinitialize the variable every time you click the button.


#3

Yeah I know, any ideas how to solve it??


#4

Hello @RobertLinde, You have to initialize it just once. You can Initialize it like this:

export class yourPageClass{
  
  count: number = 0; //Here you'll initialize it just once and we'll access it in the function

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  countup()
  {
	this.count++;  //instead of reinitializing, we are using already initialized variable
	console.log(JSON.stringify(this.count));
  }


Hope this will help you.
Cheers!!!


#5

Unrelated sidenote, you don’t have to convert it to JSON when passing to console.log.


#6

I knew bro, i just changed the required code :slightly_smiling_face:


#7

Yeah you’re good :ok_hand:. I was just letting the OP know.


#8

Thanks a lot guys, also thanks for the hint about JSON :slight_smile: