问题
I am using Ionic Cordova to build an iPhone app. I have a login screen username input and password input plus a submit button. I cannot make to focus on password input after typing the username and tap "return".
My login.html looks like this:
<ion-list >
<ion-item>
<div id="loginlogo"></div>
</ion-item>
<ion-item>
<ion-label stacked>Username</ion-label>
<ion-input type="text" name="usernameInput" (keyup.enter)="focusAndGo()" [(ngModel)]="usernameInput"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Password</ion-label>
<ion-input type="password" id="passwordInput" name="passwordInput" [(ngModel)]="passwordInput"></ion-input>
</ion-item>
<ion-item><button (click)="logincontrol()" ion-button color="light" block>Login</button></ion-item>
</ion-list>
and my login.ts look like this:
@ViewChild('passwordInput') nameInput;
focusAndGo()
{
var input = document.getElementById('passwordInput');
input.focus();
this.nameInput.setFocus();
//this.nameInput.nativeElement.focus();
//this.nameInput.nativeElement.setFocus();
//this.passwordInput.focus();
//alert(event.keyCode );
//if( event.keyCode ==13)
//{
//this.passwordInput.focus;
//}
}
I tried everything that is commented above. I cannot get cursor to move to next input.
回答1:
I think you should prevent default behaviour before setting focus,
send $event to your function
<ion-input type="text" name="usernameInput" (keyup)="focusAndGo($event)" [(ngModel)]="usernameInput"></ion-input>
and use preventDefault() before setting focus
focusAndGo(e)
{
e.preventDefault();
var input = document.getElementById('passwordInput');
input.focus();
}
回答2:
it's a old post but a posibility is make a directive like
@Directive({
selector: '[next-tab]',
})
export class NextTabDirective{
@Input('next-tab') nextControl: any;
@HostListener("keydown.enter", ["$event"])
onEnter(event: KeyboardEvent) {
if (this.nextControl.focus)
{
this.nextControl.focus();
event.preventDefault();
return false;
}
}
}
then you can use a form like
<form [formGroup]="dataForm" (submit)="submit(dataForm)">
<input formControlName="data1" [next-tab]="data2">
<input #data2 formControlName="data2" [next-tab]="data3">
<input #data3 formControlName="data3">
<button type="submit">Click</button>
</form>
来源:https://stackoverflow.com/questions/47951591/how-to-go-to-next-input-by-tapping-return-key-on-an-iphone-ipad-with-ionic2