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

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

Add an element to an array using the `push` method in JavaScript

I am currently studying the code for creating a canvas circle motion trail effect. I am a bit puzzled by the push(x:Pos,y:Pos) within thestoreLastPosition() function in the sample code provided below: ctx = canvas.getContext('2d'); var xPos = - ...

calling object functions using additional parentheses

After reviewing the passport.js documentation, I came across this piece of code: app.get('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!u ...

JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below: function onlyDecimal(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

Manipulating the value of an array obtained from an API alters its data when trying to log it in the render function of a React TSX component

My program can fetch data from an API I created using a component that interacts with the backend: import React, { Fragment, useEffect, useState } from 'react' import { Button, Stack } from '@mui/material'; import TabsComponent from &ap ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...

React app experiencing crashes due to Material UI Select component issues

I am facing a challenge while trying to incorporate a material ui select component into the React application I am currently developing. Whenever I attempt to add a select functionality to a form, it results in a crash. Despite following the example provid ...

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

Issue encountered with ngFor: 'Identifier not defined __type does not have any such member'

Recently, I successfully implemented a sub-component that allows users to dynamically add and remove a set of controls to and from a collection. The inspiration for this solution came from reading through this particular thread on Stack Overflow. While ev ...

Displaying object properties within another object obtained from an API request in a React component

Dealing with API data can be tricky, especially when there are nested objects involved. I've encountered an error message stating 'undefined is not an object (evaluating 'coin.description.en')', as the description property of the c ...

Interceptor causing Angular HTTP Client to return null value

Here are two examples of the code output in the console. In order to return an observable for an interceptor, I converted a local storage promise into an observable using switchmap. However, I am still receiving null as the value. The function is wrapped i ...

Issue with Angular 4 Routing: Links are opening in new window instead of within router-outlet

I am currently facing an issue while trying to display the SuburbDataComponent HTML on the DASHBOARD-SIDE-PANEL-COMPONENT.HTML. When I click on Dashboard, it opens a new window but only displays the SuburbDataComponent.html without showing the side panel ...

Building a custom CellRenderer in AGGrid using TypeScript within a React environment

Currently, I am utilizing React along with TypeScript and attempting to create a custom CellRenderer in AGGrid. My code is structured like this: PriorityCellRenderer.tsx import React from 'react'; function PriorityCellRenderer(props:any) { co ...

The uncertainty surrounding the usage of checkboxes in D3.js

I am faced with the challenge of adding checkboxes to multiple groups within an SVG, each containing a circle and text element. I have attempted to accomplish this by using D3 to append foreignObject tags and then add checkboxes to each group. The code I h ...

Exploring the possibilities of combining mixitup with Vue.js 2.0 Component

Struggling to implement mixitup on vue.js; however, every time I check the mixitup target, it shows 0 elements in the container (mixer.getStatus().totalShow) Below is my complete vue.js component code: <template> <section class="main-co ...

Ways to eliminate the white background gap between pages on ionic

While developing an app using Ionic, I encountered a strange issue. Everything runs smoothly on a browser, but when testing the app on an Android 5 device, I noticed a white background appearing between pages. The app loads correctly with the custom splas ...

Adjust the height, width, and color of the "kendo-switch" widget

I am looking to customize the height, width, and color of the "kendo-switch" component. I attempted to modify the element's style directly, but it did not have the desired effect. What would be the most effective approach for achieving this customiza ...

Strategies for efficiently retrieving delayed ajax data to display in a Rails view

When working with an API action that takes around 10 seconds to retrieve data, I typically use an alert to ensure the data is successfully fetched. However, my main concern is how to effectively transmit this data to a Rails view for displaying purposes. B ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...