Enabling and disabling features in Angular 7 based on a click event

Utilizing Angular 7 along with Typescript 3.1.1

Aim

The objective is to implement click events that cannot be triggered again until the previous click event is completed, regardless of the outcome.

Illustration

<div>
    <span *ngFor="let a of [1,2,3,4,5,6]" (asyncClick)="onClick(a)">
    </span>
</div>

Here, asyncClick replaces click. asyncClick accepts a Promise<any> and utilizes .then on it. During the period waiting for then to execute, the button should be disabled.

Obstacle Faced

Given that asyncClick can be attached to different elements such as div, span, button, input, a, img, or even a component, I aim to avoid creating a component for each type as it lacks flexibility.

Progress Made So Far

A directive has been crafted to detect click events using

@HostListener('click', ['$event'])

However, the challenge lies in obtaining the promise for the click event. An example is

<div asyncClick (asyncClick)="myOnClick()"></div>
, where when myOnClick is triggered, the promise to await is missing.

myOnClick (num: number): Promise<any> {
    return Promise.resolve();
}

Answer №1

To accomplish this, utilize Observable 'Subject'.

Utility:

@Injectable({providedIn: 'root'})
export class asyncService {

   fetchUserData(){
     return from(this.http.get());
   }
}

Instruction:

  @Output() debounceClick = new EventEmitter();
  private actions = new Subject();

  constructor() { }

  ngOnInit() {
    this.actions.pipe(
      debounceTime(500),
      asyncService.fetchUserData()
    ).subscribe(e => this.debounceClick.emit(e));
  }

  @HostListener('click', ['$event'])
  actionEvent(event) {
    event.preventDefault();
    event.stopPropagation();
    this.actions.next(event);
  }

Source:

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

Is there a comparable alternative to <ion-forward>?

I have a brand new module where users input information across 3 separate pages. Page 1: basic details with a continue button Page 2: additional info with another continue button and Page 3: the final submission Currently, when navigating back from Page ...

While working on a project that involves TypeScript, Material-UI, and Formik, I encountered an error that originated from

I recently downloaded a project from the following site: https://codesandbox.io/s/gn692 Upon encountering some errors that I couldn't resolve on my own, I decided to download this project to see how it's implemented. Surprisingly, it runs smoothl ...

Ways to bypass certificate verification

Every time I make a request from the server to fetch data, I encounter a certificate error. GET https://ip:5001/api/cards/online net::ERR_CERT_COMMON_NAME_INVALID To resolve this issue, I made the decision to bypass certificate verification. Can you provi ...

What could be causing Angular to not show the outcome? Why is it that only the complete-handler is being triggered?

Just wanted to share my current setup: ASP.NET Core 8 Web API .NET Core 8 backend for frontend Angular SPA served inside a bff using typescript (ES2022) Request flow: -> SPA (Cookie) -> BFF (Token) -> API Struggling with the SPA to display or i ...

How do I create a standalone .ts file with Angular 9?

Just diving into Angular development and eager to create a standalone .ts file without having to generate an entire component. Can anyone guide me on how to achieve this using ng generate? Scenario: During the application build process, I need to write th ...

Experiencing Issues with npm-install in Angular 8 - How to Troubleshoot the

My App is encountering issues with running npm-install after transferring it to a different computer. Below is the content of my package.json file: { "name": "lunaticgodsinfo", "version": "0.0.0", "scripts ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Issue: The function "MyDocument.getInitialProps()" needs to return an object containing an "html" prop with a properly formatted HTML string

Check out my project on GitHub at https://github.com/Talita1996/NLW4 To start the project, I used the command yarn create next-app project_name I made changes to some files by modifying their extensions and adding new code Next, I added typescript to the ...

Navigate to the middle of a DIV container in Angular 7

Is there a way to programmatically scroll to the center of my element on both the Y and X axes when a specific function is executed? My HTML structure includes the following (I am aiming to scroll to the middle of #viewport): </div> <div # ...

When you refresh the page, the number of items in the cart displayed on the navbar always shows 0

When using my angular application, I encountered a problem with adding movies to a cart. Although I can successfully add them to the cart and see the correct number of movies reflected in the navbar, upon refreshing the page, the count resets to 0. Here i ...

Evaluating string combinations in JavaScript using valid comparisons

After choosing values on the screen, two variables store their value. var uval = '100'; var eval = '5'; There are 2 combinations with values: let combination1= 'u:100;e:1,4,5,10' let combination2 = 'u:1000;e:120,400,500, ...

Can a generic type be utilized to instantiate an object?

In my code, I have a class named Entity as shown below: class Entity { constructor(readonly someValue: string) {} someFunction() {} } Now, I am trying to create a class that will handle these entities and be able to create instances of them. In or ...

The View is not reflecting changes in the Variable

Is there a way to disable all the buttons when selectedplace is null in the Dialog, as it currently works when the Dialog first starts but remains activated all the time when the option is changed? I have attempted the following: Customized HTML: ...

How can I pass DOCUMENT in Angular?

In my directive, I use dependency injection to access the DOCUMENT and set up an event listener: constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit() { this.document.addEventListener('click', this.clicked, true); } @Bound ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Structural directives allow for the declaration of variables

In my Angular application, I've implemented a custom structural directive called `IfDataDirective` as follows: @Directive({ selector: '[appIfData]' }) export class IfDataDirective { private hasView = false; @Input() set appIfData( ...

Angular - Implementing a debounce feature for event handling

Currently, I am utilizing the mouseenter and mouseleave events to control the opening and closing of my sidenav within the app. However, I have encountered issues because when hovering over the container quickly, these events are triggered multiple times ...

Tips for setting ngModel and name attributes in an angular test for a custom component

Just getting started with angular. I recently developed a custom component that implements the ControlValueAccessor to allow developers to easily access its value. Here's an example of how it can be used: <app-date [label]="'Date 2&apos ...

Guide on correctly setting up and utilizing refs for a themed functional component in TypeScript and React Native

Primary Objective: I aim to have two text inputs where pressing return on the first one will shift the focus to the next input. Let's begin with the configuration (using TypeScript). I have a customized text input with specific color settings, and I ...

Semantic-ui-react cannot be located by Docker

I am a beginner when it comes to docker and I'm looking to create a React app, specifically using TypeScript, inside a docker container. In order to do this, I need to incorporate semantic-ui-react into my project. I followed the instructions provide ...