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

The type 'SVGPathSeg' cannot be assigned to type 'EnterElement' because the property 'ownerDocument' is not present in type 'SVGPathSeg'

I'm attempting to replicate this example using the d3-ng2-service service on Angular 5. Component: OnInit code: let d3 = this.d3; let d3ParentElement: Selection<HTMLElement, any, null, undefined>; let d3Svg: Selection<SVGSVGElement, any, n ...

I'm curious as to why it's requesting an ID in the newTask function. I followed the tutorial exactly and encountered the same error

An issue has occurred in the project, displaying the following error: Error: src/app/components/add-task/add-task.component.ts:32:25 - error TS2345: Argument of type '{ text: string; day: string; reminder: boolean; }' is not assignable to paramet ...

The TypeScript error occurs when trying to set the state of a component: The argument 'X' cannot be assigned to the parameter of type '() => void'

When I attempt to call setState, I encounter a TypeScript error. Here is the code snippet causing the issue: updateRequests(requests: any, cb:Function|null = null) { this.setState( { requests: { ...this.state.requests, ...

Can anyone explain why the Splice function is removing the element at index 1 instead of index 0 as I specified?

selectedItems= [5,47] if(this.selectedItems.length > 1) { this.selectedItems= this.selectedItems.splice(0,1); } I am attempting to remove the element at index 0 which is 5 but unexpectedly it deletes the element at index ...

What is the best way to delay Angular for 5 seconds before initiating a page transition?

Just a quick inquiry - is there a way to have Angular wait for 5 seconds before redirecting to a different page? I attempted to implement this functionality within my function, but it doesn't appear to be functioning as expected: setTimeout(() => ...

Securing Angular 2: How to Safely Store PassportJS Tokens

How can I retrieve the token generated from the provided express code snippet after a user logs in via Facebook, is stored in the database, and is redirected to /auth/facebook/callback? I want to fetch this token using either callbacks, promises, or obse ...

What is the process for setting up a signup and sign-in page in Angular 12 while incorporating local storage for authentication?

After saving signup data using local storage, I am now looking to utilize that information on the login page for user authentication. What specific code should be implemented on the login page in order to verify whether the individual has signed up or no ...

Challenge encountered when setting new values to an object depending on its existing values

I am facing an issue with a data object that stores values and their previous values. The keys for the previous values are suffixed with ":previous" e.g. foo and foo:previous. However, I encountered a type error when trying to assign values to the previous ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

Troubleshooting common issues while setting up React Native with TypeScript

After carefully following the steps outlined in this guide on configuring a React Native project using TypeScript: https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native, I encountered a total of fifteen errors from the ...

Reversing a Firebase list in Angular 2 after inserting a new item: A step-by-step

I am currently looking for a solution to reverse my Firebase list in real-time. For instance: Let's say I have the following Firebase list: {apple, orange, banana}; == After reversing => {banana, orange, apple} If I were to add a new item (with ...

Concealing Dropdown Box Information Based on a Customized List in Angular

Is there a way to remove an item from a dropdown list once it has been selected? For example, if I have a dropdown box with options 'Dog', 'Lion', and 'Cat', how can I make it so that once I select 'Dog', it will no ...

Creating a back button for returning to the previous page

I have created an Angular application that retrieves data from an API. However, I am facing an issue where the data is lost when navigating to another route and then returning to the table route. Is there a way to switch routes without losing the data? &l ...

Accessing the map in an Angular 6 service via Leaflet

Embedding a map into my Angular 6 app service has been a bit tricky. Currently, I'm passing it as an argument when calling an init function in the service and providing it via Subject from the component after fetching data from the store. However, som ...

What is the best way to predefine a value for a checkbox in Angular?

Here is the code snippet I am currently using: <input type="checkbox" [(ngModel)]="i.checkt" [ngModelOptions]= {standalone:true} (change)="recovery(i.checkt,i.TherapeuticArea)"> {{i.TherapeuticArea}} I have encountered an issue where setting stan ...

Troubleshooting a problem with Angular2 involving the This.http.get function

Currently, I am delving into Angular 2 and have set up an ASP.NET WebApi locally hosted in IIS at http://localhost:8081/ping. The API call successfully returns a string serialized as a JSON Object. Below is the code for my service: import { Injectable } ...

Issue encountered while implementing a recursive type within a function

I've created a type that recursively extracts indices from nested objects and organizes them into a flat, strongly-typed tuple as shown below: type NestedRecord = Record<string, any> type RecursiveGetIndex< TRecord extends NestedRecord, ...

“What is the process of setting a referenced object to null?”

Here is an example of the code I'm working with: ngOnInit{ let p1 : Person = {}; console.log(p1); //Object { } this.setNull<Person>(p1); console.log(p1); //Object { } } private setNull<T>(obj : T){ obj = null; } My objective is to ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Navigating JSON Objects in Ionic 2

Example of my JSON array structure [{ label: "Interests", datatype: "check", lookupname: "null", order: "05", options: [ 0:{id: "01", value: "Photography"} 1:{id: "0 ...