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

Resetting FormArray upon selecting a new value from a dropdown in Angular 4 Reactive Forms

I am facing an issue where I need to choose a warehouse before being able to view the ingredients. The problem arises when attempting to switch warehouses, as I need to clear the form array or the entire form since each warehouse has a different set of i ...

Property does not exist on object error is thrown by Angular httpClient.getResult

constructor(private http: HttpClient) { } ngOnInit() { this.http.get('url').subscribe(data => { console.log(data); console.log(data.login); }); } } When looking at the data in the console, I noticed that the property &ap ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Add a module to the main module or main component within the project

I have integrated a third-party library to manage the layout of my Angular application. I am considering importing it either in app.module.ts (the root module) or in app.component.ts (the root component). Do you think there would be any significant diff ...

Using useEffect with promises causing TypeScript errors

useEffect(login, []) In this case, the login function returns a promise and the useEffect hook is triggered without expecting a return value. However, TypeScript shows errors like: Argument of type '() => Promise<void>' is not assi ...

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...

Tips for arranging Angular Material cards in columns instead of rows

I am currently developing a web application using Angular, and I've encountered an issue while trying to display cards in a vertical layout rather than horizontally. My goal is to have the cards fill up the first column (5-6 cards) before moving on to ...

Avoiding loading certain images within an *ngFor loop

Is it possible to control the loading of images within an *ngFor loop in Angular? Load image with index X first Fire a function once all other images have loaded The goal is to prioritize the display of important images while optimizing bandwidth usage. ...

What is the reason why the swiper feature is malfunctioning in my React-Vite-TS application?

I encountered an issue when trying to implement Swiper in my React-TS project. The error message reads as follows: SyntaxError: The requested module '/node_modules/.vite/deps/swiper.js?t=1708357087313&v=044557b7' does not provide an export na ...

What causes the node_modules folder to become corrupted when publishing an AspNetCore2 project with Visual Studio?

During the development of my AspNetCore project using Kendo, Angular5, and AspNet Mvc, everything was running smoothly. However, when trying to publish the project, I encountered a strange issue where it breaks. https://i.sstatic.net/2xQ1Q.png I then cam ...

Font Awesome functions properly on one Angular component but not on the second one

I've encountered a strange issue while working on my Angular project. About a month ago, I added a component with a form that included some inputs along with Font Awesome icons. The code snippet is provided below. <div class="field"> ...

Creating dynamic meta tags in Angular using server side rendering

I have developed an Angular application with Server-Side Rendering. Before deploying the final result to Azure SWA, I utilize the prerender command. One of the components in my application is a blog post component, and here is the code snippet: import { C ...

Typescript - ensure only one specific value is in an array of length N

Is there a way to require the 'foo' literal, while allowing the array to have any shape (i.e. not using an X-length tuple with pre-defined positions)? type requireFoo = ??? const works: requireFoo = ['bar','foo'] //This shoul ...

Unexpected artifacts are being introduced to the build folder by the compiler

Currently, I am following the steps outlined in this Getting Started guide to set up the installation of tsoa. According to their instructions, I have created a routes.ts folder and placed it under /build: /build /routes.ts Next, in /src/app.tsx, I mak ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

Oops! The system encountered a problem: the property 'modalStack' is not recognized on the type 'NgxSmartModalService'. Maybe you meant to use '_modalStack' instead?

Currently, I'm facing an issue while attempting to run ng build --prod in my Angular 6 project. I have also incorporated the NgxSmartModal package for handling modals. Unfortunately, the build process is failing and I can't seem to figure out why ...

What's New with Material 3 in Angular 17?

Even though I've taken the time to read all of the documentation at https://github.com/material-components/material-web/blob/main/docs/quick-start.md, I'm still struggling to figure out how to incorporate this into my Angular 17 project. I went ...