Angular 6 - execute function on either click event OR focus event

I am trying to figure out how to call a function from a component only when it is clicked or focused. Below is a snippet of the components HTML:

<div class="form-add-new__input-box">
     <input
           #commentCategories
           class="form-add-new__category-box"
           (click)="toggleCategoriesSelection($event)"
           (focus)="toggleCategoriesSelection($event)"
           (keyup)="searchCategory($event.target.value)"
           tabindex="0"
           placeholder="Search or select">
     <span class="icon-arrow-down"></span>
</div>

and the corresponding function:

public toggleCategoriesSelection(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    this.categoriesSelectOpen = !this.categoriesSelectOpen;
}

My current issue is that toggleCategoriesSelection is being called twice on the first click. I tried using something like this, but it didn't work:

(click | focus)="toggleCategoriesSelection($event)"

Is there another way to achieve this functionality?

Answer №1

Include a stop propagation method in your click and focus events.

 <input
           #commentCategories
           class="form-add-new__category-box"
           (click)="$event.stopPropagation();$event.preventDefault();toggleCategoriesSelection($event)"
           (focus)="$event.stopPropagation();$event.preventDefault();toggleCategoriesSelection($event)"
           (keyup)="searchCategory($event.target.value)"
           tabindex="0"
           placeholder="Search or select">
     <span class="icon-arrow-down"></span>

I hope this information is helpful!

Answer №2

It may not be necessary to invoke the toggleCategoriesSelection function on both the click and focus events simultaneously. However, if you do wish to do so, you can implement it as shown below.

This code snippet addresses the issue of frequent function calls happening within a short period, known as the smallTimeout.

timeOutExceeded = true // initial value

public toggleCategoriesSelection(event: Event): void {
    if (this.timeOutExceeded) {
        // your logic
        this.timeOutExceeded = false;
        setTimeout(() => {
            this.timeOutExceeded = true;    
        }, smallTimeout);
    }
}

You might also want to explore techniques like RXJS debouncing for handling similar scenarios.

https://medium.com/aviabird/rxjs-reducing-number-of-api-calls-to-your-server-using-debouncetime-d71c209a4613

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

Hamburger Menu in Bootstrap not functioning as expected

Despite following each step meticulously for implementing the Hamburger menu in the navbar, I encountered an issue. The navbar collapses when resizing the window but fails to open upon clicking it. Below is a sample code snippet for reference. It utilizes ...

In a specific Angular project, the forget password feature is experiencing issues with sending email links in the Chrome browser. Interestingly, this issue only occurs the first

I'm currently working on an Angular 6 application that has been deployed with the domain "www.mydomain.com/". All the routes are functioning properly, such as "www.mydomain.com/dashboard" and "www.mydomain.com/products". However, there is an issue w ...

Utilize Hostbinding in Angular to Inject Style Declarations

Is there a way to efficiently inject multiple style declarations into a component using the @HostBinding decorator? I've been attempting the following: @HostBinding('style') get style(): CSSStyleDeclaration { return { background: &apo ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

Make an indirect mention of a distant JavaScript web address

Our company is looking to incorporate Rollup with Angular 4/Typescript and NPM, and we have a specific set of requirements: Various teams develop JS libraries that need to be centralized, similar to a CDN These libraries are hosted at remote URLs and sho ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

The act of importing the MatButtonModule module serves no purpose

I am developing an Angular application with the Material design framework. My goal is to incorporate the material button module into my project. Including it in app.module.ts is done as follows (excerpt from code): import { MatTableModule } from '@ ...

Destructuring an array of strings for use as parameters

Hey guys, I'm working with an array of keys here Example 1: let keyArray = ['x', 'y', 'z'] I'm trying to find a way to use these keys as parameters without repeating them multiple times. Do you have any suggestions ...

Trouble incorporating SCSS color variables into Angular component_IMPORT issue

My Angular 9 app has a folder structure that includes: | app | app.component.ts | app.component.html | app.component.scss | assets | _colors.scss The _colors.scss file contains definitions for two colors: $red: #DA0000; $blue: #1080E1; In the a ...

Unable to proceed with npm install due to absence of a package.json file in the directory

Let me share my recent experience: I decided to update the @angular-cli version on my local machine, but it ended up causing a series of issues (like 'Cannot find module '@angular/compiler-cli/ngcc'). Despite trying various solutions, none s ...

Errors may arise in Typescript when attempting to block the default behavior of DataGrid onRowEditStop

Hey there! I'm new to posting questions here and could use some help. I'm encountering a minor issue while trying to prevent the default behavior of the "Enter" key in the "onRowEditStop" method of the DataGrid component. Here's my code sni ...

Is ngOnDestroy in Angular 2 triggered on page refresh, or only when navigating away from the component?

Can anyone clarify whether the ngOnDestroy method in Angular 2 is triggered on page refresh or only when navigating away? ...

Removing an attachment from the attachment object array nestled within a comment object array nested inside another object array

I am currently grappling with the challenge of removing an attachment from an array of attachments within a nested structure of comment objects. Despite several attempts, I have yet to find a solution that works effectively. export class CommentSection{ ...

A guide on implementing a "Select All" trigger in mat-select with Angular8/Material

Here is the code I have created: <mat-form-field appearance="outline"> <mat-label>Handler Type</mat-label> <mat-select multiple [(value)]="handlerType"> <mat-option *ngFor="let handler of handlerT ...

TS - deduce the specific type of a key value without receiving a union type

Welcome to the coding playground: Click here to start coding Let's talk about a scenario where a function is expected to return some value based on an input argument. The challenge arises when there are keys with the same name but different types re ...

When importing the Ionic Native File, the JavaScript File object cannot be used simultaneously

When attempting to use the javascript file object, I encountered an issue because the ionic native file object already uses the same key File Here is an example: import { File } from '@ionic-native/file'; @Component({ selector: 'page-ho ...

Facing a blank page with no errors displayed during the HTML rendering process in Angular version 6

One of the most frustrating aspects of working with Angular is the lack of information provided when there is a render error in an HTML page. Instead of specifying which page the error is in, Angular defaults to the route page and provides no further detai ...

What are the best methods for testing a function containing multiple conditional statements?

I have a complex function that I want to showcase here, it's quite simple but for some reason, I'm struggling with writing unit tests for it. I don't need the exact unit test implementation, just a general approach or tips on how to handle i ...

Removing Firebase Users using Angular2/Ionic2

I'm currently working with Ionic2/Angular2 and I've been searching for a guide on deleting users from Firebase. If anyone has any useful examples, I would greatly appreciate the assistance. Thank you. ...

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...