skip to Main Content

I have a angular application where there is a toolbar on top. There are some button on the toolbar which is working fine except when the user clicks it twice. For example, when the following button is clicked twice, it saves the data twice on the server.

   <a class="nav-link" (click)="buttonClicked()" href="#">
                    <i class="fas fa-save" title="History"></i>
   </a>

How can I stop this from happening.. May be I need to disable the button for few milliseconds in order to avoid accident clicking… But not sure how can I achieve this…

Thanks in advance.

2

Answers


  1. Disable the button after the first click, until the API call is done or errors out. I use pointer-events: none; to prevent clicks, and opacity: 0.5; to make the button seem disabled. But you can use this to solve your issue.

    CSS:

    .disabled {
        pointer-events: none !important;
        opacity: 0.5 !important;
    }
    

    HTML:

    <a class="nav-link" (click)="buttonClicked()" href="#" [ngClass]="{'disabled': isDisabled }">
         <i class="fas fa-save" title="History"></i>
    </a>
    

    TS:

    isDisabled = false;
    ...
    
    ...
    buttonClicked() {
        this.isDisabled = true;
        this.someService.save().subscribe({
            next: () => {
                this.isDisabled = false;
                ...
            },
            error: () => {
                this.isDisabled = false;
                ...
            },
        });
    }
    
    Login or Signup to reply.
  2. You can use rxjs and the throttleTime operator. It will skip the n requests sended in between x amout of time.

    throttleTime emits the source Observable values on the output Observable when its internal timer is disabled, and ignores source values when the timer is enabled. Initially, the timer is disabled. As soon as the first source value arrives, it is forwarded to the output Observable, and then the timer is enabled. After duration milliseconds (or the time unit determined internally by the optional scheduler) has passed, the timer is disabled, and this process repeats for the next source value. Optionally takes a SchedulerLike for managing timers.

    Here is an example https://stackblitz.com/run?devtoolsheight=50&file=index.ts

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search