Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element.

I have successfully implemented the first part of adding "display: block" when the element is reached via the tab key. But I am unsure about how to handle removing it when the user tabs out.

@HostListener('document:keydown.tab', ['$event'])onKeydownHandler(event: KeyboardEvent) {
if (event.key === "Tab" && (event.target as Element).classList.contains('some-class')) {
  this.renderer.addClass(this.test?.nativeElement, 'd-block');
}}

I would appreciate some assistance. Is there a more effective approach to achieve this functionality without relying solely on host listeners?

Answer №1

You have the option to utilize the focus event in order to switch a variable on and off, while the blur event can be used to toggle it back. You can also listen for the mouseover and mouseout events and leverage ngStyle to toggle the styles! Similarly, you can apply this technique to ngClass as well!

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  styles: [
    `
    h1,.test {
      background-color: lightblue;
    }
    .d-block {
      display: block;
    }
    `,
  ],
  template: `
  <div tabindex="1">test</div>
  <div tabindex="1">test</div>
  
  <span class="test" tabindex="1" [ngClass]="{'d-block': isFocus2}" (mouseover)="isFocus2 = true;" (focus)="isFocus2 = true;" (mouseout)="isFocus2 = false;" (blur)="isFocus2 = false;">Hello from {{ name }}!</span>
  <div tabindex="1">test</div>
  <div tabindex="1">test</div>
    <h1 tabindex="1" [ngStyle]="{'display': isFocus ? 'block' : 'inline'}" (mouseover)="isFocus = true;" (focus)="isFocus = true;" (mouseout)="isFocus = false;" (blur)="isFocus = false;">Hello from {{ name }}!</h1>
  `,
})
export class App {
  name = 'Angular';
  isFocus = false;
  isFocus2 = false;
}

bootstrapApplication(App);

Check out the example on stackblitz

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

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Enhancing DOM Elements in a React Application Using TypeScript and Styled-Components with Click Event

I've been working on an app using React, Typescript, and styled components (still a beginner with typescript and styled components). I'm trying to create a simple click event that toggles between which of the two child components is visible insid ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

Setting multiple route parameters for a single segment

Let's jump right into the problem at hand. Is there a way to define multiple route parameters for one segment as shown in the route below: The Routes: { path: 'planlist/:departure_:destination/:date', component: ReservationComponen ...

What is the best way to add attachments to the clipboard in a Chrome extension?

One possible way to achieve this is by using the navigator.clipboard.write API, but keep in mind that this API is not available to background pages of Chrome extensions. A method I attempted involved creating a blob like this: let blobFinal = null; // ...

The exclusion feature in TSLint does not seem to be functioning properly

It seems that the ts lint -e/--exclude feature is not functioning properly, or perhaps I am doing something incorrectly. I currently have tslint 4.5.1 installed. Whenever I attempt to use the CLI with tslint -e path_to_file, it gives me an error stating ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Distinguishing between selecting rows and selecting checkboxes in Mui Data Grid

Is there a way to differentiate between clicking on a row and clicking on the checkboxes? I want to be able to select multiple rows by clicking anywhere in the row except for the checkbox column. When clicking outside the checkbox column, I would like to p ...

What is the process for marking a form field as invalid?

Is it possible to validate the length of a field after removing its mask using text-mask from here? The problem is that the property "minLength" doesn't work with the mask. How can I mark this form field as invalid if it fails my custom validation met ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...

Navigating through content on a screen can be accomplished in two

Is it feasible to incorporate both horizontal and vertical scrolling on a website using anchor tags? I recently created a website with horizontal scrolling for each main page. Within some of these main pages, there are subsections that I would like to hav ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

Combining Turn.js with AJAX for an interactive web experience

I've been experimenting with turn.js and struggling to find an example of loading dynamic pages with content via ajax. While the page is loading, it's not displaying all the results. For a JSON result from the controller, click here. <div clas ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

Tips for utilizing the patchValue method within a dynamic FormArray in Angular

When working with the first case (check out the DEMO link), patchValue() function can easily manipulate the select drop-down menu in a reactive FormGroup(), where only FormControl() is used. However, in the second case, I need to achieve the same functiona ...

Strategies for increasing a value within an asynchronous function

I'm facing an issue with incrementing the variable loopVal inside a promise. I've tried to increment it without success. Any ideas on how to make this work? const hi = function(delay) { let loopVal = 1; return new Promise((resolve, reject) ...