Using Enter key to move to the next field under ng-template on Angular 7+

105 Views Asked by At

I am getting the following : Cannot read properties of undefined (reading 'focus')

So, I console logged the nextField.nativeElement , using console.log(nextField.nativeElement) and got undefined

my .html file :

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

my .ts file :

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();
    }
  }
} 

I am expecting when my mouse pointer in on input1 , I hit 'Enter' key using keyboard it will move to input2.

1

There are 1 best solutions below

0
Eliseo On

Be careful!!! When you use ViewChild (or ViewChildren) you get an ElementRef (1)

@ViewChild('input1') input1: ElementRef;

But when you use the template reference variable in .html is an 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();
    }
  }

(1) when the template reference variable is applied to an HTML tag, if you use a template reference variable in a component is the component, and if the html tag have a directive that "exportAs" we can use

<div my-directive #templateRef="MyDirective">