Postpone the initial click action triggered by the specified directive

Is it possible to create a directive that prompts for confirmation when a button is clicked? This would involve storing the original event and only executing it once the user confirms their choice.

A similar behavior has been mocked here:

https://stackblitz.com/edit/angular-6wnvjk?file=src%2Fapp%2Fapp.component.html

(Although this example uses a Timeout instead of confirmation, the concept remains the same)

What approach should be taken to save the original event and then trigger it after the timeout/confirmation process is completed?

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[confirm]'
})
export class ConfirmDirective {

  constructor() { }

  @HostListener('click', ['$event'])
  onClick(event: MouseEvent) {
    console.log('handler from directive');
    // 1 - Would like to store original event
    const originalEvent = () => {};
    // Would like to call it later
    setTimeout(() => {
      originalEvent();
    })
  }

}

Answer №1

To create a custom directive that intercepts clicks and triggers them only when a certain condition is met, you can follow this approach:

@Directive({
    selector: '[confirm]',
})
export class ConfirmDirective implements OnInit, OnDestroy {
    @Output() confirmed = new EventEmitter();
    private clicks = new Subject();
    private subscription: Subscription;

    constructor() {}

    ngOnInit() {
        this.subscription = this.clicks
            .pipe(
                switchMap((event) => confirm('Do you agree?') ? of(event) : null)
            )
            .subscribe((e) => this.confirmed.emit(e));
    }

    ngOnDestroy() {
        if (this.subscription) this.subscription.unsubscribe();
    }

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

Example of how to use this directive:

<button confirm (confirmed)="doSomething()">Click</button>

Give it a try!

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

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

Identifying misspelled names in shared resources textures during PIXI.js loading

Our game utilizes TypeScript, Pixi.js, VSCode, and ESLint. We maintain a dictionary of image files as follows: export function getAllImages(): {name: string, extension: string}[] { return [ {name: 'tile_lumber', extension: '.svg ...

Facing a problem with running npm start on jHipster

I am currently working on a jhipster project on my MacBook Pro running macOS Mojave v.10.14.4. After successfully compiling with npm start, the code continues to compile multiple times without any changes. Eventually, it throws the following error: DONE ...

What is the reason behind this build error I am encountering while using react-three-xr?

I'm having trouble understanding this error message. What steps can I take to resolve it? Although I have included three-xr in my react app, I am encountering the following error: Failed to compile. ../../node_modules/@react-three/xr/src/DefaultXRCon ...

What is the method for utilizing data binding to modify a portion of a class name string with an ISO country code of your choice

Is there a way to dynamically change the country flag icon displayed on an element using the flag-icon stylesheet? This CSS provides country flags based on ISO codes, like so: <span class="flag-icon flag-icon-gr"></span> This code would displ ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

Unable to locate module src/ in Node.js TypeScript

I'm encountering issues with non-relative imports in my node.js / typescript application. Here is my tsconfig: { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": ["dom", "es6", "es2017", "esnext.asynciterable"], "s ...

Using webpack to generate sourcemaps for converting Typescript to Babel

Sharing code snippets from ts-loader problems may be more suitable in this context: Is there a way to transfer TypeScript sourcemaps to Babel so that the final sourcemap points to the original file rather than the compiled TypeScript one? Let's take ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

What is the reason behind line-height not affecting the clickable area when reduced?

I have been working on a personal project where I added thumbnails for images that can be scrolled through and clicked to set the main image. However, I encountered a strange issue. To demonstrate the problem, I created a Stackblitz project here: https:// ...

Issue TS1259: The module "".../node_modules/@types/bn.js/index"" can only be imported as the default using the 'esModuleInterop' flag

Currently, I am utilizing Hiro Stack.js which I obtained from the following link: https://github.com/hirosystems/stacks.js/tree/master/packages/transaction. For additional information, please refer to . Even when attempting to compile a fully commented out ...

What is the method to transfer the outcome of a GET request into a POST request?

My task involves sending a GET request to retrieve information from . When the request is made, it generates a random image and returns a JSON object that includes details such as "fileSizeBytes" and "url". My goal is to extract the "url" value and then ...

Problem with moving functions from one file to another file via export and import

I currently have the following file structure: ---utilities -----index.ts -----tools.ts allfunctions.ts Within the tools.ts file, I have defined several functions that I export using export const. One of them is the helloWorld function: export const hel ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Error message TS2339 in Typescript: The property '__super__' is not found on the type '($element: any, options: any) => any'

Having trouble with Javascript code inside typescript. $.fn.select2.amd.require([ 'select2/data/array', 'select2/utils' ], function (ArrayData, Utils) { /* tslint:disable */ function CustomData ($element, opti ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...