在 Angular 7+ 上使用 Enter 键移动到 ng-template 下的下一个字段

问题描述 投票:0回答:1

我得到以下信息:

Cannot read properties of undefined (reading 'focus')

因此,我使用 console.log(nextField.nativeElement) 控制台记录了 nextField.nativeElement 并得到了未定义

我的 .html 文件:

<ng-template #myTemplate>
  <table>
    <tr>
      <td>
        <input (keydown.enter)="onEnterPressed($event, input2)" #input1 />
      </td>
    </tr>
    <tr>
      <td>
        <input #input2 />
      </td>
    </tr>
  </table>
</ng-template>  

我的.ts 文件:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
})
export class YourComponent {
  @ViewChild('input1') input1: ElementRef;
  @ViewChild('input2') input2: ElementRef;

  onEnterPressed(event: KeyboardEvent, nextField: ElementRef): void {
    if (event.key === 'Enter') {
      event.preventDefault(); 

      nextField.nativeElement.focus();
    }
  }
} 

我期待当我的鼠标指针位于 input1 上时,我使用键盘按“Enter”键,它将移动到 input2。

angular focus directive enter
1个回答
0
投票

小心!!! 当您使用 ViewChild(或 ViewChildren)时,您会得到一个 ElementRef

@ViewChild('input1') input1: ElementRef;

但是当你在.html中使用模板引用变量时是一个

HTMLElement

<!--as you use input2, you pass an HTMLElement-->
<input (keydown.enter)="onEnterPressed($event, input2)" #input1 />
<input #input2 />
//e.g.
{{input2.value}}

  //see that received as argument an "Event" and an HTMLElement
  onEnterPressed(event: Event, nextField: HTMLElement): void {
    if ((event as KeyboardEvent).key === 'Enter') {
      event.preventDefault(); 

      nextField.focus();
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.