How can I integrate keydown.control with a unique click function in Angular?

Is there a way to choose multiple number elements in random order and save them to an array by holding down the control key (CTRL) and clicking on the element? For example, selecting 2 and 4 out of 5. I tried different methods but couldn't figure out how to combine the click event with @Hostlistener.

https://i.stack.imgur.com/kNWgi.png

<div class="nums">
   <div *ngFor="let tempNum of [1, 2, 3, 4, 5]">
      <span class="num" (click)="onNumClick(tempNum)">{{ tempNum }}</div>
   </div>
</div>
@Hostlistener('window.keydown.control', ['$event'])
onKeyDown(event: KeyboardEvent) {
   console.log('Control key clicked');
}

onNumClick(num: number) {
   this.selectedNums.push(num);
}

Answer №1

An easy solution to this problem would be to simply check if the click event includes the ctrlKey flag, and adjust the behavior accordingly.

<div class="numbers">
  <div *ngFor="let number of [1, 2, 3, 4, 5]">
      <span class="number" 
      (click)="select(number, $event.ctrlKey)">{{ number }}</span>
  </div>
</div>

I've opted for using a Set instead of an array to prevent duplicates efficiently.

readonly selectedNumbers = new Set<number>();

select(number: number, selectMultiple: boolean): void {
    if (!selectMultiple) {
        this.selectedNumbers.clear();
    }
    this.selectedNumbers.add(number);
}

Keep in mind that this method may not work well on mobile devices. For mobile users, you may need to provide an alternative like checkboxes or longpress functionality.

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

Uploading Files with Django Rest Framework and Angular 2

I am working with Django Rest Framework and Angular 2 to implement a file upload feature. Below is my code structure for handling files. Can anyone point out where I might be going wrong? Any help is greatly appreciated. Thank you! Django file: view cla ...

Dockerized Nginx: Struggling with location configuration issues

Here is the docker file: FROM nginx:1.17.4-alpine # copy artifact build from the 'build environment' COPY ./dist /usr/share/nginx/html/ COPY ./default.conf /etc/nginx/conf.d/ # expose port 80 EXPOSE 80 # run nginx CMD ["nginx", "-g", "daemon o ...

Headers cannot be modified after they have been sent to the client in Node.js and Angular

I am working on developing login and registration services using Nodejs Express. Every time I make a request in postman, I consistently encounter the same error: https://i.stack.imgur.com/QZTpt.png Interestingly, I receive a response in postman (register ...

NPM Alert: Outdated lockfile detected The package-lock.json file appears to have been generated using a previous version of NPM

package-lock.json causing issues when upgrading from Angular 9 to 10 Is there a way to generate a new package-lock.json file and successfully upgrade Angular 9 to 10? I'm looking to update from Angular 9 to 10 and troubleshoot the error related to p ...

What is the process for clearing cache in inversifyJS?

In my simple application, I am using express server along with TypeScript. Initially, I can successfully reach my endpoint, but after updating the model, the old data persists. I have attempted the suggested approach mentioned here: How to disable webpage ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

guide to utilizing npm/yarn with tsx react

I've recently made the switch to using TypeScript with React, but I'm encountering a problem. After installing certain packages from npm or yarn, I'm having trouble using them in my .tsx components. The error message suggests looking for @ty ...

Error: JSON parse error - unexpected character 'a' at index 1

I'm encountering an issue while attempting to change the album title from "cars" to "car". The error message I keep receiving is: SyntaxError: Unexpected token a in JSON at position 1. Any ideas on what might be causing this problem? Below is the cu ...

What are the best practices for styling a component in Fluent UI when using React and TypeScript?

I'm attempting to set a background color for this specific div element: import * as React from 'react' import { Itest } from '../../../../../models' import { getPreviewStyles } from './preview.style.ts' type IPreviewP ...

Click on the button to generate a PDF report using Internet Explorer 11

After encountering some challenges with printing a PDF report specifically on IE 11, I am reaching out for help. The code snippet below works perfectly in Chrome, but when it comes to IE 11, everything falls apart. Just to provide some context, I am develo ...

tips on how to shade a column in the material data table according to a specific condition when the table is first loaded

Is there a way to automatically highlight certain rows in the angular material data table based on specific column values when the table loads? Let's take a look at an example component below: @Component({ selector: 'table-basic-example', ...

Strange activities observed during the management of state in react hooks, where the splice() function ends up eliminating the

My current setup involves maintaining a state to handle the addition of new JSX elements: const [display, setDisplay] = useState<IDisplay>({ BookingFormDropDown: [], } ); I have a function in onClick() which adds an elem ...

Is it possible to use the Optimistic Hook with boolean values?

I am facing an issue with a switch component where the checked value is updated only after refetching the data when the user is changed to an admin status. Currently, there is a delay when clicking the switch as it takes time to load and then updates. It ...

When working with TypeScript in Node, the module ""http"" does not have a default export available

const httpModule = require('http'); httpModule.createServer((req, res) => { res.end('Hello World'); }).listen(3000, () => console.log('Server is running on port 3000')); I've installed @types/node but ...

Add CSS properties to child elements that are not of a specific selector, while styling their descendants without any restrictions

Seeking assistance for an Angular application, but the query also pertains to CSS principles in general. In my Angular project, I have a main component containing several child components, all with standard view encapsulation. Specifically, I am looking t ...

Can classes from an external package be imported into an Angular library within an Angular app using Openlayers?

I am currently developing an Angular library that configures an OpenLayers map as an Angular component. The component is functioning properly, but I need to access classes and constants from a package imported by the library, specifically OpenLayers. To w ...

Creating a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follo ...

Utilize forRoot to pass configuration data

When using Angular, I encountered a challenge in passing configuration data to a custom library. Within the user's application, they are required to provide config data to my library through the forRoot method: // Importing the custom library import ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Having trouble with subscribing to a template in Ionic framework

I'm attempting to showcase an image from Firebase storage using the following code: Inside my component : findImg(img) { this.storage.ref('/img/' + img).getDownloadURL().subscribe( result => { console.log(result); ...