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.
Be careful!!! When you use ViewChild (or ViewChildren) you get an ElementRef (1)
But when you use the template reference variable in .html is an
HTMLElement(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