如何自动关注下一个领域?

时间:2019-10-17 15:15:33

标签: angular typescript ionic-framework

我要用户在单独的字段中键入SMS接收到的代码。

这种方式:

<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field1" name="field1" (ionChange)="eventIonChange($event, 2)" (ionFocus)="eventIonFocus($event)" autofocus="true"></ion-input>
<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field2" name="field2" (ionChange)="eventIonChange($event, 3)" (ionFocus)="eventIonFocus($event)"></ion-input>
<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field3" name="field3" (ionChange)="eventIonChange($event, 4)" (ionFocus)="eventIonFocus($event)"></ion-input>
<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field4" name="field4" (ionChange)="eventIonChange($event)" (ionFocus)="eventIonFocus($event)"></ion-input>

那么,当用户在每个字段中键入一个caharcter时,如何更改焦点?

我正在尝试类似的事情:


field1:string = '';
field2:string = '';
field3:string = '';
field4:string = '';

...

eventIonFocus(e) {
  e.target.value = '';
}

eventIonChange(e, nextElement) {
  if(nextElement){
    let element = (<HTMLInputElement>document.getElementById('field2'));
    element.setFocus();
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用 ViewChild 进行以下操作。

HTML

 <ion-input #field1 type="text" inputmode="numeric" [(ngModel)]="smsCode.first" maxlength="1" (ionChange)="eventIonChange(2)"></ion-input>
 <ion-input #field2 type="text" inputmode="numeric" [(ngModel)]="smsCode.second" maxlength="1" (ionChange)="eventIonChange(3)"></ion-input>
 <ion-input #field3 type="text" inputmode="numeric" [(ngModel)]="smsCode.third" maxlength="1" (ionChange)="eventIonChange(4)"></ion-input>
 <ion-input #field4 type="text" inputmode="numeric" [(ngModel)]="smsCode.fourth" maxlength="1"></ion-input>

 <button ion-button (click)="onSubmit()">SUBMIT</button>

TS

export class HomePage {

  @ViewChild('field1') field1;
  @ViewChild('field2') field2;
  @ViewChild('field3') field3;
  @ViewChild('field4') field4;

  smsCode: any =  { first: '', second: '', third: '', fourth: '' };

  constructor() {

  }

  ngAfterViewInit() {
    setTimeout(() => this.field1.setFocus(), 500 )
  }

  eventIonChange(next) {

    switch(next) {

      case 2:
        this.field2.setFocus();
        break;

      case 3:
        this.field3.setFocus();
        break;

      case 4:
        this.field4.setFocus();
        break;

    }
  }

  onSubmit() {
    // Do your implementation with user inputs here
    console.log(JSON.stringify(this.smsCode, null, 2));
  }

}

变化很大。但是你会同意的。

Find StackBlitz Demo.