我是Ionic的新手。我正在使用Ionic框架3.我的问题是我不知道如何访问由ion-input指令包围的输入值。我想访问我创建的自定义指令的输入框的值。
ElementRef会帮助获取输入框的值吗?我试了但是失败了。请指导我以正确的方式访问custom指令中输入框的值。以下是我的代码......
我的自定义指令代码 - 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代码
<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>
答案 0 :(得分:3)
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)
获取最新价值,但这取决于您的需求。