freeNinja
freeNinja

Reputation: 375

Handle Tab event

How can I handle a Tab keypress event in Angular 2?

I took this from the Angular docs to get the keyCode. It works well when I press the other keys, but when I press Tab nothing happens.

import { Component } from '@angular/core';

@Component({
 selector: 'my-app',
 template: `<input (keyup)="onKey($event)">
            <p>{{values}}</p>`
})

export class AppComponent {
  values = '';
  onKey(event: any) { 
  this.values += event.keyCode+ ' | ';
  }
}

Also, is this the correct way to do it in Angular 2?

<input ng-keydown="($event.keyCode == 9) && 
       signal('something')" />

Upvotes: 31

Views: 61367

Answers (3)

Hodglem
Hodglem

Reputation: 634

I was having a similar problem. I initially tried using $event in the template, but after some reading here, it seems passing $event isn't something the Angular team encourages (see the link for detail). They recommend using template reference variables. This was fine until I tried using tab and I ended up getting what @freeNinja was getting; tab would work but then direct focus to the top of the page. @ Günter Zöchbauer answer in the comments above worked for me. Adding false after the method call stopped the focus from being transferred. (keydown.tab)="saveEntry(i, newCost.value); false

Upvotes: 4

Yoav Schniederman
Yoav Schniederman

Reputation: 5391

<input (keypress)="someFunction($event.target.value)"/>

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658255

 <input (keydown.Tab)="onKey($event)">

Upvotes: 70

Related Questions