Change behaviour of enter key in a phone - Angular

2019-08-21 09:27发布

I am working with inputs but I am not really sure about how is the configuration of the navigation done (I guess that it are predefined behaviours).

I am not in the last input the enter key goes to the next one. This one is working as I want. enter image description here

Nevertheless, when I am on the last input, when I press enter, it automatically clicks on the next button. enter image description here

This is what I am trying to avoid. Is there any way to change this behaviour? Just to close the keyboard or to click on another button?

I have tried with keyup.enter and it pseudo works. It calls to the method but also clicks on the next button

HTML

<input
          type="text"
          class="form-control"
          id="validationCustomSurname"
          placeholder="e.g. Lopez"
          required
          (keyup.enter)="onNavigate(1, 'forward')"
          [(ngModel)]="values.store.surname"
          name="surname"
        />

This method should work on a phone, so I guess that keydown is not an option since $event.code does not give me any code in the phone.

1条回答
女痞
2楼-- · 2019-08-21 09:48

Some time ago I make a directive see stackblitz that you apply in a div (or in a form) in the way

<form [formGroup]="myForm" (submit)="submit(myForm)" enter-tab>
    Each input or button add a reference variable #nextTab like
    <input name="input1" formControlName="input1" #nextTab/>
    <button type="button" #nextTab/>
</form>

The directive use ContentChildren to add a keydown.enter to all the components that have #nextTab to focus to the next control

export class EnterTabDirective {
  @ContentChildren("nextTab") controls: QueryList<any>
  nextTab

  constructor(private renderer: Renderer2, private el: ElementRef) {
  }
  ngAfterViewInit(): void {
    this.controls.changes.subscribe(controls => {
      this.createKeydownEnter(controls);
    })
    if (this.controls.length) {
      this.createKeydownEnter(this.controls);
    }
  }
  private createKeydownEnter(querycontrols) {
    querycontrols.forEach(c => {
      this.renderer.listen(c.nativeElement, 'keydown.enter', (event) => {
        if (this.controls.last != c) {
          let controls = querycontrols.toArray();
          let index = controls.findIndex(d => d == c);
          if (index >= 0) {
            let nextControl = controls.find((n, i) => n && !n.nativeElement.attributes.disabled && i > index)
            if (nextControl) {
              nextControl.nativeElement.focus();
              event.preventDefault();
            }
          }
        }
      })
    })
  }
查看更多
登录 后发表回答