Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Value Input field Ionic 2

I have a tiny question.

I'm using this HTML code:

<ion-input id="amount" type="number" ></ion-input>

<button (click)="setinput()">Set Value</button>

And this TS code:

setinput(){
var input= document.getElementById("amount") as HTMLInputElement;
input.value=42;
console.log("amount");
console.log(input.value);
}

My console tells me, that the number got changed. But the updated value wont be displayed in my input field. Do you have any suggestions?

Thanks in Advance!

L. Trembon

like image 473
Luca Trembon Avatar asked Nov 09 '16 17:11

Luca Trembon


People also ask

What is ionChange?

(ionChange) : This event fires only when user change value of input field. if user copy and paste same value it will not get fired. but if user enters different value then it will fire. because it matters values of input field.


1 Answers

You can do it like that:

page.html

<ion-input id="amount" type="number" [(ngModel)]="value"></ion-input>
<button (click)="setInput()">Set Value</button>

page.ts

export class Page {
  value: number = 0; // Default is 0

  constructor() {}

  setInput() {
    this.value = 42;
  }
}

By using [(ngModel)]="value" you bind the value variable to that input field. That way it is always updated. If you change it in the UI, it is immediately updated "in the code". And when you update it in your code, it automatically updates in the UI.

You should probably read an Angular 2 tutorial before you continue working on your app. Angular provides many tools to make that sort of thing a lot easier.

like image 69
Andreas Gassmann Avatar answered Oct 31 '22 22:10

Andreas Gassmann