Ekos
Ekos

Reputation: 725

Angular 4 - Focus on next element with Enter

this question has been asked before for AngularJS and Jquery however I need to do this in Angular 4 and its slightly different.

Situation:

I have a component with a table (Tablecomponent). The table is filled with input fields for users. Now I want to tab through these input fields with Enter Key as well instead of Tab Key only.

I have found this solution somewhere else but it doesnt work because "element" has no function "focus()"

onKeyUp($event) {
if ($event.keyCode === 13) {
  const element: any = event.srcElement.nextElementSibling;
  if (element == null) {
    return;
  } else {
    element.focus();
  }

I'm not sure but I believe the first thing to do is to get the next Element ("input" field here) and simply "focus" it.

Upvotes: 3

Views: 6884

Answers (1)

Aniruddha Das
Aniruddha Das

Reputation: 21688

Angular have a element reference elementRef you can use and it will be more accurate to hit an event like key event in angular application.

// add it to your compoenent
constructor(private elementRef: ElementRef) { }

Then you can focus it using

this.elementRef.nativeElement.focus();

Upvotes: 2

Related Questions