Reputation: 375
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
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