Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button:

import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core';

@Directive({
  selector: 'button[type=submit]'
})
export class PreventDoubleSubmit {

  @HostBinding() disabled:boolean = false;

  @Input() valid:boolean = true;      

  @HostListener('click') 
  onClick() {
      console.log("aaa");
    this.disabled = true;
  }
}

This directive is then incorporated into a shared module:

import { NgModule } from '@angular/core';
import { PreventDoubleSubmit } from '../shared/prevent-double-submit.directive';

@NgModule({
    declarations: [
        PreventDoubleSubmit
    ],
    exports: [
        PreventDoubleSubmit
    ]
})
export class SharedModule{}

Upon implementing this in the app.module, I noticed that when clicking on the button for the first time, it gets correctly disabled. However, the original actions associated with the form no longer execute. It seems like the directive has taken precedence and is preventing any other action from occurring.

The form tag being used is:

<form (ngSubmit)="onSubmit(f)" #f="ngForm" class="generalForm"></form>

In the corresponding TypeScript file, the code simply consists of:

onSubmit(form: NgForm) {
        console.log("This is the code I want to perform");
}

Answer №1

I made some modifications to your directive

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

@Directive({
    selector: 'button[name=saveButton]'
})
export class PreventDoubleSubmit {

    @HostBinding() disabled: boolean = false;

    @Input() valid: boolean = true;

    @HostListener('click')
    onClick() {
        console.log("The save button is now disabled");
        this.disabled = true;
    }
}

After that, I added it to app.module

@NgModule({
    imports:[...],
    declarations: [
...
PreventDoubleSubmit,
...
]
export class AppModule { }

It is working perfectly for me.

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

What is the best way to differentiate between the legend and chart when working with three separate

I have encountered an issue with my pie charts. The first chart has 10 legends displayed below it, while the second chart only has 4 legends. When I adjust the padding to accommodate the 10 legends in the first chart, the names of the 4 legends in the se ...

Angular default route with parameters

Is it possible to set a default route with parameters in Angular, such as www.test.com/landing-page?uid=123&mode=front&sid=de8d4 const routes: Routes = [ { path: '', redirectTo: 'landing-page', pathMatch: 'full' }, ...

There seems to be a compatibility issue between Angular 16 and Bootstrap 5 styling

In my angular.json, I have defined my styles in the following way: "styles": [ { "input": "node_modules/bootstrap/dist/css/bootstrap.min.css", "bundleName": "ltrCSS" }, { "input": "node_mod ...

Navigate to a different component within Angular

Is there a way in Angular to scroll to a component using a button placed in another component? Below is the code snippet for the first component: <div id='banner' class="col-5 offset-1 d-flex justify-content-center align-items-cen ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

Preventing the compilation process from overwriting process.env variables in webpack: A step-by-step guide

Scenario I am currently working on developing AWS Lambda functions and compiling the code using webpack. After reading various articles, I have come to know that the process.env variables get automatically replaced during compilation. While this feature ...

Is it possible to implement typed metaprogramming in TypeScript?

I am in the process of developing a function that takes multiple keys and values as input and should return an object with those keys and their corresponding values. The value types should match the ones provided when calling the function. Currently, the ...

Simple and quickest method for incorporating jQuery into Angular 2/4

Effective ways to combine jQuery and Angular? Simple steps for integrating jQuery in Angular2 TypeScript apps? Not sure if this approach is secure, but it can definitely be beneficial. Quite intriguing. ...

Accessing attributes of a parent class object from within a child object

Imagine having four tabs within an Angular component, each with its own set of criteria for being displayed. Here's a high-level overview of the scenario. export class DisplayTabs { foo: true; bar: false; tabs: { 'A': { order: 1, g ...

Enhancing performance in Angular 6 with trackBy in ngFor: Does it work?

Discover the Benefits of Using trackBy with ngFor in angular 6 for Enhanced Performance <app-analysis-item *ngFor="let element of analyses" [analysis]="element" (deleteAnalysisEvent)="onAnalysisDeleted($event)"> </ ...

What could be causing the lack of change detection triggering in nested dynamic components?

I'm encountering an issue with change detection in a nested dynamic component that involves content projection. For some reason, the child component is not being automatically triggered for change detection, necessitating manual intervention for every ...

What could be causing my Mongoose controller to not be executed?

I am currently working on developing an API using Mongoose and Express. I have successfully set up several routes that are functioning properly. However, I am facing an issue with a specific route that is intended to search for a model called Subassembly b ...

return to the previous mat tab by using the browser's back button

Currently working on an Angular project, I am faced with the challenge of configuring the Mat Tab to close the active tab and return to the previously accessed tab when the browser's back button is clicked. How can I accomplish this without relying on ...

Return the previous value if the filter function returns false in RxJs

In an attempt to optimize performance and reduce unnecessary requests to the server, this code checks if values exist in the store before making additional requests. While the overall logic functions correctly, there is an issue where if the filter returns ...

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...

Guide to combining an Angular 2 (angular-cli) application with Sails.js

I am looking to integrate the app created using angular-cli with Sails.js. My background is in PHP, so I am new to both of these frameworks. What are the steps involved in setting them up together? How can I execute commands like ng serve and/or sails li ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Combining angular's CLI project with a groovy Gradle application

I'm in the process of merging the seed project from angular-cli with my Gradle-packaged Java application, deployed on a Tomcat server. How can I successfully combine the Angular build with the Gradle build? Additionally, where is the ideal location t ...

What is the most efficient way to update data multiple times by mapping over an array of keys in a react hook?

My question might not be articulated correctly. I'm facing an issue with dynamically translating my webpage using Microsoft's Cognitive Services Translator. I created a react hook for the translator, which works well when I need to translate a si ...

Steps for automatically incrementing a number when adding an item to an array using Angular

I am currently working on adding values to an array and displaying them in the view. Everything is functioning correctly, but I would like to include an auto-incrementing number with each item. The initial array is stored in a data.json file. [ {"i ...