Jananath Banuka
Jananath Banuka

Reputation: 673

How to get input text value in ionic

I'm trying to get input text value and store it in a variable named input in ionic. But I tried and failed. Can anyone please tell me what I have faulty done?

This is my HTML

  <ion-content>
  <ion-list>
    <ion-item> 
        <ion-label stacked>display</ion-label>
      <ion-input type="text" text-right id="input" ></ion-input>
    </ion-item>    
  </ion-list>
  </ion-content>

and this is my home.ts in ionic

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

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

  constructor(public navCtrl: NavController) {
    var input=document.getElementById('input').nodeValue;
    document.getElementById('seven').innerHTML=input;
  }
  
}

Upvotes: 20

Views: 75491

Answers (3)

Oren Levy
Oren Levy

Reputation: 11

In Ionic 5 - The way to get the value of an ion-input value when focusing:

<ion-input (ionFocus)="onFocusPlace($event)"></ion-input>

onFocusPlace(event){
    this.value = event.target.value;
}

Upvotes: 1

Ofir G
Ofir G

Reputation: 754

<ion-content>
  <ion-list>
    <ion-item> 
      <ion-label stacked>display</ion-label>
      <ion-input type="text" text-right id="input" [(ngModel)]="inputValue"></ion-input>
    </ion-item>    
  </ion-list>
</ion-content>

// ===

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
    inputValue: string = "";
    constructor(public navCtrl: NavController) {}

    someFunction() {
        // here you can use the 'this.inputValue' and get the value of the ion-input 
    }

}

we use the two way binding the value of ion-input with the class member inputValue,

about ngModel

whan you need to access on the value of the input, check the value of inputValue.

here you can see an exemple I wrote on StackBlitz

Two-way binding is a combination of both property binding and event binding as it is a continuous synchronization of data/values from presentation layer to component and from component to the presentation layer.

Since this is a two way binding we have to use both the brackets - [ ( ) ]. Also ngModel is a directive which is used to bind the data both ways.

Upvotes: 16

Sajeetharan
Sajeetharan

Reputation: 222552

Actually you seems to be using angular not angularjs, use [(ngModel)]

 <ion-input type="text" [(ngModel)]="name" text-right id="input" ></ion-input>

and inside the component,

name:string;

so whenever you need the value , you can use.

console.log(this.name);

Upvotes: 33

Related Questions