Check the status of the caps lock key upon initialization of the directive

One challenge I am facing is how to determine the caps lock state when initializing a directive. The current setup only detects changes after a key press, but what if the user enters the page with caps lock already activated? Here is the existing code for the directive (credit to Vega's answer):

import { Directive, EventEmitter, HostListener, OnInit, Output } from '@angular/core';

@Directive({
    selector: '[capsLock]',
})
export class CapslockDirective implements OnInit{
    @Output('capsLock') capsLock: EventEmitter<boolean> = new EventEmitter<boolean>();
    capsOn!: boolean;

    ngOnInit(): void {
      // detect caps lock state here
    }

    @HostListener('window:keydown', ['$event'])
    onKeyDown(event: KeyboardEvent): void {
        this.capsOn = event.getModifierState && event.getModifierState('CapsLock');
        this.capsLock.emit(this.capsOn);
    }
    @HostListener('window:keyup', ['$event'])
    onKeyUp(event: KeyboardEvent): void {
        this.capsOn = event.getModifierState && event.getModifierState('CapsLock');
        this.capsLock.emit(this.capsOn);
    }
}

Can Angular handle detecting caps lock in its initial state?

Answer №1

As far as I know, checking the state of a key in JavaScript is not possible and I cannot recall seeing this feature in TypeScript either. Another approach would be to create a boolean variable in your parent component that gets updated when the Caps Lock key is pressed or released, and then pass this variable to your directive using an input binding:

isCapsOn = false;

@HostListener('document:keydown', ['$event']) 
onKeyDown($event:KeyboardEvent):void {
   ... check if Caps Lock key has been pressed
   ... if so, set this.isCapsOn to true;
};

@HostListener('document:keyup', ['$event']) 
onKeyUp($event:KeyboardEvent):void {
   ... check if Caps Lock key has been released
   ... if so, set this.isCapsOn to false;
};

Then, in your parent HTML:

<div capsLock [capsOn]="isCapsOn" (capsLock)="yourMethod"...

Lastly, in your directive:

export class CapslockDirective implements OnInit{
    @Output('capsLock') capsLock: EventEmitter<boolean> = new EventEmitter<boolean>();
    @Input() capsOn: boolean;

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

Encountered an error while trying to upgrade Angular from version 9 to 10: The package '-e' is not recognized as a dependency

Anyone else run into this problem while upgrading an Angular app from version 9 to 10? The error message reads: ng update @angular/core@10 @angular/cli@10 I tried searching online but couldn't find any solutions that addressed my specific issue. ...

What is the best practice for updating the state of a web component in a manner that can be tracked by history with vaadin-router?

I have a straightforward LitElement custom component that I would like to incorporate an "editing" state into. Although I already possess all the necessary information from the server, I am hesitant to introduce a new component solely for displaying an edi ...

Wondering how to leverage TypeScript, Next-redux-wrapper, and getServerSideProps in your project?

Transitioning from JavaScript to TypeScript for my codebase is proving to be quite challenging. // store.ts import { applyMiddleware, createStore, compose, Store } from "redux"; import createSagaMiddleware, { Task } from "redux-saga"; ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Redirect unmatched URLs to index.html in Django for Angular app

Currently, I have set up a django server along with an angular app. When I launch the angular app and navigate through different sections using the links provided within the app, everything works smoothly. However, if I try to directly access a specific s ...

Is a node server necessary for utilizing Angular 2's asynchronous component loading in a production environment?

Currently, I am in the process of utilizing webpack to compile my files. However, I find myself unsure if I fully comprehend the workflow that is involved. My main objective is to implement code splitting for my files and then load them on specific routes ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

Eliminate the use of type assertion when verifying if a value is included in a union

I have a unique scenario where I am using a union type that involves an array. I need to check the values at run-time, but TypeScript is requiring me to use a type-assertion in this case. Take a look at the following code: const Pets = ["dog", &q ...

Switch up the component's style based on the route being accessed

Is there a way to dynamically load CSS styles in a component based on URL parameters? The idea is that the user will access the page using a URL structure like SOME_URL/{screenSize}/{type}. While the component remains the same, the CSS styling should chang ...

Exploring Angular2 components featuring setInterval or setTimeout functions

I have a basic ng2 component that interacts with a service to retrieve carousel items and automatically cycle through them using setInterval. Everything functions properly, but I encounter the error "Cannot use setInterval from within an async test zone" w ...

Failure to Generate stats.json File When Building Angular 6 with --stats-json Flag

Currently, I am facing an issue with generating the stats.json file for my Angular 6 application. Despite trying a few different methods, the file is simply not being created. It seems that my system specifically requires "npm run" before every Angular CLI ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

Updating an Angular Signal established by an RxJs stream within a service: Best practices

Within my Angular application, there is a service class named ProjectsService that handles all project-related data. It effectively manages a feed of tasks and includes functionality for liking those tasks as well. The service contains two important signal ...

How should a React Testing Library wrapper be properly typed in a TypeScript environment?

There's this code snippet from Kent C. Dodd's library that I find extremely helpful import * as React from 'react' import {render as rtlRender} from '@testing-library/react' import {ThemeProvider} from 'components/theme& ...

Utilizing Angular-dependent subscriptions in conjunction with forkJoin for efficiently modifying and processing data within code blocks

I have a subscription that relies on the outcome of a previous subscription. I am utilizing forkJoin to avoid nesting them: this.service.service1().pipe( flatMap((res1) => this.service.service2(res1)) ).subscribe((res2) => { // Perform actio ...

encountering issues while trying to set up an Angular project

I encountered an issue in my Mac's terminal while trying to create a new Angular project. Here is the command I entered in the terminal: ng new ProjectName The error message I received: npm WARN deprecated <a href="/cdn-cgi/l/email-protection ...

Node.js E2E test for endpoint involving an asynchronous operation that is not being properly handled

Currently, I am working on developing an API in Node.js using NestJS. One of the endpoints within this API calls two asynchronous services. The first service is awaited and its result is then returned in the response. However, the second service is allowed ...

Issue Arising from Printing a Custom Instruction in a Schema Generated Document

When dynamically adding a directive, the directive is correctly generated in the output schema. However, it seems to be missing when applied to specific fields. Here is how the directive was created: const limitDirective = new graphql.GraphQLDirective({ na ...

Is it a common issue that sound.stop() doesn't seem to function properly, while sound.play() operates successfully within Howler

I am having trouble utilizing Howler.js in Reactjs with typescript. While I can successfully play the sound, pausing or stopping it seems to be an issue. Below is the code snippet: This component takes all the audio details as props. I used console.log() ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...