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 of the input box 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 of the input box 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>
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[phonenumber]' // Attribute selector
})
export class PhonenumberDirective {
inputElement: any;
constructor(private element: ElementRef) {
console.log('Hello PhonenumberDirective Directive');
}
@HostListener('keydown', ['$event']) onkeydown(event) {
this.inputElement = this.element.nativeElement.getElementsByTagName('input')[0];
console.log(this.inputElement.value)
}
}
Get the input and then access the value from that.
You might also want keyup
@HostListener('keyup', ['$event']) onkeydown(event)
To get the latest value, but that depends on your needs.