首页 文章

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

提问于
浏览
0

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

ElementRef会有助于获取输入框的值吗?我试了但是失败了 . 请指导我以正确的方式访问custom指令中输入框的值 . 以下是我的代码......

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>

1 回答

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

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

    你可能也想要 keyup

    @HostListener('keyup', ['$event']) onkeydown(event)
    

    要获得最新 Value ,但这取决于您的需求 .

相关问题