Listening for combinations of keys pressed using HostListener

I've been attempting to detect when a user presses the Shift+Tab key combination on the keyboard, but for some reason I can't get the event to trigger.

@HostListener('keyup', ['$event'])
@HostListener('keydown', ['$event'])

onkeyup(event) {
  if (event.keyCode == 16 && event.keyCode == 9) {
    this.isShift = true;
    console.log("On Keyup " + event.keyCode);
  }
}

onkeydown(event) {
  console.log("On KeyDown" + event.keyCode);
}

Answer №1

While Frank Modica's solution is effective, leveraging Angular's key event filtering and pseudo-events offers a more organized and streamlined approach:

@Directive({
    selector: '[keyHandler]'
})
export class KeyHandlerDirective {

    @HostListener('keydown.shift.tab', ['$event'])
    onKeyDown(e) {
        // You can use preventDefault() if necessary
        // e.preventDefault();
        console.log('shift and tab');
    }
}

// In the template:
<input type="text" keyHandler />

To explore further examples of how pseudo-events function, check out this resource.

Answer №2

This solution is effective for handling the specified key event:

@Directive({
  selector: '[test-directive]'
})
export class TestDirective {
  @HostListener('keydown', ['$event']) onKeyDown(e) {
    if (e.shiftKey && e.keyCode == 9) {
      console.log('shift and tab');
    }
  }
}

<input type="text" test-directive />

Keep in mind that using the keyup event can be problematic as pressing the Tab key may cause the element to lose focus. As a result, the keyup event might trigger on a different element. Therefore, depending on your requirements, the use of keydown could be more suitable for handling events on the current element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

Adding strings in Typescript

I have the following code snippet: let whereClause = 'CurLocation =' + GS + ' and Datediff(DD,LastKYCVerified,GetDate()) >= 180 and CreditCard = ' + 'ACTIVE ' + &ap ...

Troubleshooting the issue with mocking the useTranslation function for i18n in JEST

Currently, I am facing an issue with my react component that utilizes translations from i18next. Despite trying to create tests for it using JEST, nothing seems to be getting translated. I attempted to mock the useTranslation function as shown below: cons ...

Adjust the size of a map on an HTML page after it has

Currently, I am utilizing Angular 2 to create a simple webpage that includes a Google 'my map' displayed within a modal. <iframe id="map" class="center" src="https://www.google.com/maps/d/u/0/embed?mid=1uReFxtB4ZhFSwVtD8vQ7L3qKpetdMElh&ll ...

Achieve HTTPS with angular-cli when running ng serve

It seems like the code snippet below is not working as expected. ng serve --ssl true --ssl-key <key-path> --ssl-cert <cert-path> Even when creating the Certificate and key by placing them in the default ssl directory, there is still no effect ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Display the concealed mat-option once all other options have been filtered out

My current task involves dynamically creating multiple <mat-select> elements based on the number of "tag types" retrieved from the backend. These <mat-select> elements are then filled with tag data. Users have the ability to add new "tag types, ...

Display the first item last in an *ngFor loop in Nativescript Angular

I'm facing some confusion with the sorting of an array in JavaScript. Although the index, last, and first seem to be correct, the result is not as expected. Versions @angular/core: 4.1.0 nativescript-angular: 3.1.3 typescript: 2.4.0 Expected 1234 ...

The not-null constraint is violated in the "id" column because of a null value when using Sequelize Typescript

My Database Setup Journey Recently, I embarked on a database adventure where I decided to use Sequelize-Typescript to assist me with all the heavy lifting in terms of database operations. The first step was creating a table called uma_tbl_users, and here ...

Having trouble directing my attention towards a Mat card when using viewchildren in Angular

My current challenge is trying to focus on a specific card from a list of mat cards Despite my efforts, I keep encountering an error that reads: Cannot read property 'focus' of undefined Access the code on StackBlitz The desired functionali ...

Is it possible to retrieve a trimmed svg image and store it on a device using react-native-svg in React Native?

I have a modified image that I want to save in my device's gallery. Can someone please guide me on how to achieve this? My project is developed using TypeScript. Modified image: https://i.stack.imgur.com/LJOY9.jpg import React from "react"; ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...

"Experience the ngx-youtube-player Angular component that allows for easy toggling between play and

My goal with ngx-youtube-player is to create a transparent div on top of it that toggles between playing and pausing the video when clicked. I am implementing this because my Angular project consists of numerous components, and one method of navigation is ...

Enter the text within the TypeScript file where the cursor is positioned

I am interested in exploring certain inferred types within TypeScript code. This would be particularly beneficial for ensuring that the inferred types are precise, specific, and accurate in correct files. Is there a way to retrieve the type at a specific ...

Managing multiple Sequelize DB connections in NestJS: A guide

I recently came across the example in the NestJS documentation regarding setting up a Sequelize DB connection. I'm curious about how to connect to multiple databases using Sequelize and TypeScript with NestJS. Can anyone provide guidance on this? ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Components in Angular 5 app hosted on Firebase fail to load

I successfully deployed my Angular 5 app to Firebase using the commands firebase init and firebase deploy. By default, the main page is pulled from the index.html file within the public directory. To ensure that my index.html was displayed, I made a chan ...

Launching a Chrome App from a website (using Angular)

In the process of building a Chrome app for Chrome OS to communicate with a serial port. Interested in integrating this Chrome App as an API within an Angular application. Seeking documentation on how to establish communication and configuration between ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Angular 8 bug: Requiring 2-3 arguments, received only 1

Currently deepening my knowledge in Angular and I encountered a situation within one of my services agree(id: string) { const headers = new HttpHeaders('Content-Type: application/json'); return this.HttpClient.put(`${this.apiUrl}/agree/` ...