How to access value of the input box surrounded by ion-input directive


#1

I am new to Ionic. I am using Ionic framework 3. My problem is that I don’t know how to access the input value which is surrounded by ion-input directive. I want to access the value for my custom directive which I created.

Will ElementRef be helpful to get the value of input box? I tried it but failed. Please guide me the right way to access the value in the custom directive. Below is my code…

My custom directive code - phonenumber

import { Directive, HostListener, ElementRef } from '@angular/core';

/**
 * Generated class for the PhonenumberDirective directive.
 *
 * See https://angular.io/api/core/Directive for more info on Angular
 * Directives.
 */
@Directive({
  selector: '[phonenumber]' // Attribute selector
})
export class PhonenumberDirective {

  constructor(private element: ElementRef) {
    console.log('Hello PhonenumberDirective Directive');
  }

  @HostListener('keydown', ['$event']) onkeydown(event) {
    let inputValue = this.element.nativeElement.textContent;
    // Here inputValue is undefined I am getting :-(
  }

}

HTML Code

<ion-list inset>
    <ion-item>
        <ion-label floating>Mobile Number</ion-label>
        <ion-input clearInput name="username" id="loginField" type="tel" required [(ngModel)]="lusername" #username="ngModel"  maxlength="10" phonenumber></ion-input>
    </ion-item>
    <div [hidden]="username.valid || username.pristine" class="alert alert-danger">
            Mobile number is required
    </div>
</ion-list>

#2

Depends what you are trying to do I guess, you can pass your the phone number model into the directive, that certainly feels like the “most Angular” way of doing it, and what I would suggest you do.

However, per your case above, once you get the native element, that’s just vanilla Javascript at that point, you have left Angular-land. And inputs don’t have textContent, because they are empty elements, they have no content. They do have values though.


#3

For any wandering visitors like me, this question is solved: https://stackoverflow.com/questions/48703377/how-to-access-value-of-the-input-box-surrounded-by-ion-input-directive