如何处理"Go"/"Enter"键盘按钮Ionic2 <ion-input>

rub*_*bmz 16 javascript key-events cordova ionic2 angular

在输入上处理"输入"或"转到"键盘键的事件是什么?输入不在表单中使用.所以点击它不会"提交".我只需要这个活动.

(在Beta 11上运行android + Ionic 2)

小智 57

我喜欢这样:

<ion-input type="text" [(ngModel)]="username" (keyup.enter)="handleLogin()"></ion-input>
Run Code Online (Sandbox Code Playgroud)

和:

handleLogin() {
    // Do your stuff here
}
Run Code Online (Sandbox Code Playgroud)


rub*_*bmz 3

正确的方法可能是使用 Ionic2 形式。我发现了这个: https: //blog.khophi.co/ionic-2-forms-formbuilder-and-validation/

否则 - 如果您“只想要“Enter”事件处理程序”,那么这非常复杂(!)并且不像您想象的那样开箱即用:

HTML:

<ion-input id="myInput" #myInput type="submit" [(model)]="textValue" (input)="setText( $event.target.value )" placeholder="Send Message ..." autocorrect="off"></ion-input>
Run Code Online (Sandbox Code Playgroud)

TS:

...
declare let DeviceUtil: any;
...
export class Component_OR_PAGE
{
    public textValue: string;
    @ViewChild( 'myInput') inputElm : ElementRef;
    @HostListener( 'keydown', ['$event'] )
        keyEvent( e )
        {
            var code = e.keyCode || e.which;
            log.d( "HostListener.keyEvent() - code=" + code );
            if( code === 13 )
            {
                log.d( "e.srcElement.tagName=" + e.srcElement.tagName );
                if( e.srcElement.tagName === "INPUT" )
                {
                    log.d( "HostListener.keyEvent() - here" );
                    e.preventDefault();
                    this.onEnter();
                    DeviceUtil.closeKeyboard();
                }
            }
        };

    ...

    setText( text )
    {
        log.d( "setText() - text=" + text );
        this.textValue = text;
    }

    onEnter()
    {
        console.log( "onEnter()" );
        this.inputText.emit( this.textValue );
        this.textValue = "";
        // ionic2 beta11 has issue with data binding
        let myInput = document.getElementById( 'myInput' );
        let innerInput: HTMLInputElement = <HTMLInputElement>myInput.children[0];
        innerInput.value = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

JS:

DeviceUtil =
{
    closeKeyboard: function()
    {
        cordova.plugins.Keyboard.close();
    }
}
Run Code Online (Sandbox Code Playgroud)