如何访问 ion-input 指令包围的输入框的值

Siv*_*tti 1 mobile-application typescript angular-directive ionic3 angular

我是离子的新手。我正在使用 Ionic 框架 3。我的问题是我不知道如何访问 ion-input 指令包围的输入值。我想访问我创建的自定义指令的输入框的值。

ElementRef对获取输入框的值有帮助吗?我尝试过但失败了。请指导我访问自定义指令中输入框的值的正确方法。下面是我的代码...

我的自定义指令代码-电话号码

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 :-(
  }

}
Run Code Online (Sandbox Code Playgroud)

HTML 代码

<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>
Run Code Online (Sandbox Code Playgroud)

小智 5

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)
  }

}
Run Code Online (Sandbox Code Playgroud)

获取输入,然后从中访问值。

您可能还需要keyup

 @HostListener('keyup', ['$event']) onkeydown(event)
Run Code Online (Sandbox Code Playgroud)

获取最新的值,但这取决于你的需求。