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

`Incorporating CSS Pseudo-elements to Customize Angular Font Awesome Icons Issue`

I successfully integrated @fortawesome/angular-fontawesome into my Angular 7 application by following the instructions provided on https://www.npmjs.com/package/@fortawesome/angular-fontawesome. Although I am able to use the icons directly, I am facing di ...

Troubleshooting auxiliary routes in Angular: why won't they work

I am facing an issue where I am trying to load components into a router outlet nested within another component. Within my ProgramComponent (with the selector app-program), I have defined a router outlet. <a routerLink="admin1">One</a> <a ro ...

How can Angular 2 e2e tests maintain respect for their execution order?

What's the best way to ensure that Angular 2 e2e tests run in the order they are declared? I am currently using Angular-cli for my project. ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

The value of the filename property cannot be determined as it is undefined

Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts" import { diskStorag ...

Hide the MaterialTopTabNavigator from view

Is there a way to hide the react native MaterialTopTabNavigator on the screen while still maintaining the swiping functionality between screens? I want the user to be able to swipe between screens but not see the tab navigator itself. const Tab = creat ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

Using Vue js and Typescript to automatically scroll to the bottom of a div whenever there are changes in

My goal is to automatically scroll to the bottom of a div whenever a new comment is added. Here's what I have been trying: gotoBottom() { let content = this.$refs.commentsWrapper; content.scrollTop = content.scrollHeight } The div containing ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

The specified type `Observable<Pet>&Observable<HttpResponse<Pet>>&Observable<HttpEvent<Pet>>` is not compatible with `Observable<HttpResponse<Pet>>`

I'm currently attempting to integrate the Angular code generated by openapi-generator with the JHipster CRUD views. While working on customizing them for the Pet entity, I encountered the following error: "Argument of type 'Observable & ...

Retrieve the output of the subscribe function in Angular 8 service

I have a service with a method that retrieves the profile image of a user. users.service.ts getPictureProfile() { const headers = new HttpHeaders({ . . .}); const options = { headers }; const body = {...}; return this.http.post(environmen ...

Steps for importing jQuery to vendor.ts in Angular 2 webpack

Currently, I am in the process of setting up my Angular 2 app using webpack. As I review the vendor.ts file, I notice this specific structure. // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; ...

Setting up the Angular 2 environment with angular-cli: A step-by-step guide

Attempting to configure environment settings using angular-cli following the guide at https://github.com/angular/angular-cli#build-targets-and-environment-files However, even after running "ng build --prod -aot", the output pages continue to display conte ...

A guide on crafting a type definition for the action parameter in the React useReducer hook with Typescript

In this scenario, let's consider the definition of userReducer as follows: function userReducer(state: string, action: UserAction): string { switch (action.type) { case "LOGIN": return action.username; case "LOGOUT": return ""; ...

Avoid activating automatic save feature in Material UI data grid

After creating a data-grid and attempting to add records, I encountered an issue where pressing the TAB key automatically saved the data when focusing on the save button without manually pressing enter. How can this behavior be prevented so that manual con ...

Checkbox selections persist when navigating between pages

I am currently working with Angular 9 and I have a list of checkboxes that need to default to true when displaying certain data. If one of these checkboxes is unchecked, it should trigger the display of specific information. The issue I am facing is that o ...

Flexbox is not properly repeating elements horizontally

I am struggling to align text boxes horizontally within ngFor loop, and I can't seem to pinpoint the mistake. Here is the HTML code from the parent component: <div class="maintenance-section"> <div class="yearly"> ...