Addressing command problems in Angular

I am experiencing an issue with a dropdown functionality. When a user selects an option and then presses either the "Delete" or "Backspace" button on the keyboard, the value from the dropdown clears which is working correctly. However, I am attempting to implement a Directive that achieves the same effect but I am facing challenges in making it work. Can anyone provide guidance on how to properly create this directive?

Thank you in advance for your help!

Below is the code snippet:

VIEW LIVE DEMO

onKeyUp(evt){
   if(evt.keyCode === 8){
     this.isShowClear = false;
     let currentElementName = evt.currentTarget.getAttribute('name');
     this.myForm.controls[currentElementName].patchValue('');
 }
}

onChange(){
this.isShowClear = true;
}

Answer №1

Check out this directive code snippet:

@Directive({
  selector: '[customDropDown]'
})
export class CustomDropDownDirective {

  @Output() updateProperty: EventEmitter<any> = new EventEmitter();

  constructor(private el: ElementRef, private control : NgControl) { }

    @HostListener('keyup',['$event'])onkeyup(event:any){
    if(event.keyCode === 8){
       let currentElementName = this.el.nativeElement.value;
      this.control.control.setValue('');
      this.updateProperty.emit(false);
    }
  }
}

Experience the LIVE DEMO where I enhanced your example. Don't forget to add your directive in app.component.ts, as it was missing in the demo causing it not to work.

Answer №2

If you want to capture key events, using the keypress attribute is a great option. Here's an example of how you can do it:

@HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;

    // You can then check the keycode to see if it is for backspace or delete,
    // and remove data from a selector with the help of NgControl.
  }

Make sure to import NgControl from @angular/core before using it.

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

Multiple components are returned with switch case

I am trying to iterate over an object and display a result based on Object.entries. However, the loop currently stops at the first return statement. Is there a way for me to capture and display all components returned simultaneously, perhaps using a vari ...

The overload signature does not align with the implementation signature when working with subclasses

Uncertain whether it's a typescript bug or an error in my code. I've been working on a plugin that generates code, but upon generation, I encounter the issue This overload signature is not compatible with its implementation signature in the resul ...

Tips on how to verify if the Angular test with native elements has produced an error

Is there a way to detect errors in an Angular test that uses native elements? The test I am running is as follows: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { MikeComponent } from './mike.component&a ...

Verify if an item is present within a separate array

To determine if an object in one array exists in another array, we can use the combination.some() method with a condition that checks for a match based on specific criteria. In the example below, the event array returns true while the event1 array return ...

What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like: function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c} // undefined b = new a(1,2) // a {foo: 1, bar: 2, yep: 3} However, I've been struggling to achieve the same in TypeScript. None of ...

Angular 2 404 Error persists despite successful retrieval of data from Oracle database using Backend Nodejs URL entered directly into the browser

Recently, I've been working on displaying data in my Angular frontend that is fetched from an Oracle DB connected to my Node backend. When I access the physical API link, the data appears and is displayed in the backend console.log. I'm wonderin ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Tips for effectively modifying the color of a mat-icon using Angular

After thoroughly reviewing the documentation, I attempted to modify the color of a mat-icon using the following code snippet: <mat-icon class="white" color="primary" svgIcon="back"></mat-icon><span class="backText">back</span> Thi ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

The error message in Angular states "Unable to destructure the 'country' property of an intermediate value as it is null"

I recently started an Angular project from scratch. When I run the default application that is created alongside the project (which is currently empty), I encounter an error in the console: "Uncaught (in promise) TypeError: Cannot destructure property &apo ...

The current version of npm for @angular 2 has not been released yet

Looking to transition from Angular 2 Beta 15 to Angular 2 RC1. Currently utilizing Visual Studio 2015. Within my npm package.json in Visual Studio, I've inputted: "dependencies": { "@angular/core": "Unavailable", } However, it displays as unav ...

Angular2: Maintaining a continuous connection for a child component to receive input from the parent component post onInit

I'm currently working on integrating an error message component into another parent component. The child component, which displays the error message, has an input attribute that the parent component uses to pass the error message. However, I've e ...

What is the best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

When I include formControlName in Angular, the select dropdown loses its default value

I seem to be facing an issue with my select element. When I include the formControlName, the placeholder "-- Select Event Type --" no longer appears (even though it is still selected in the dropdown). If I remove it, the placeholder displays but the valida ...

Utilizing AES encryption in C# and decrypting it in Angular, converting it from a byte[] / number array with the help

I am looking to securely encrypt and decrypt a byte[] in a C# API endpoint, then convert the decrypted document to base64 for viewing in a PDF viewer within an Angular 14 app. I came across this helpful guide on Stack Overflow [https://stackoverflow.com/q ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

Issue with ngModel value not being accurately represented by checkbox state in Angular 2

My issue lies with a checkbox that does not reflect its ngModel value. To provide some context, I have a Service managing a list of products and a component responsible for displaying this list and allowing users to select or deselect products. If a user d ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...

Using Long Polling with Angular 4

I am looking for a way to monitor the progress of a certain task using API calls. To achieve this, I have developed a service that executes these API calls every 1.5 seconds Main Component private getProgress() { this.progressService.getExportPr ...