I’m building an Angular application and have a custom button component that uses a directive to throttle click events. Even when the button is disabled, clicking it still triggers the function associated with the click event in the parent directive.
Here’s a simplified version of my setup:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-button',
template: `
<button [disabled]="isDisabled" (click)="onClick($event)">
<ng-content></ng-content>
</button>
`,
})
export class ButtonComponent {
@Input() isDisabled = false;
@Output() click = new EventEmitter<Event>();
onClick(event: Event) {
if (this.isDisabled) {
event.stopPropagation();
} else {
this.click.emit(event);
}
}
}
import { Directive, Output, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[throttledClick]',
})
export class ThrottledClickDirective {
@Output() throttledClick = new EventEmitter<Event>();
private isThrottled = false;
@HostListener('click', ['$event'])
handleClick(event: Event) {
if (!this.isThrottled) {
this.isThrottled = true;
this.throttledClick.emit(event);
setTimeout(() => this.isThrottled = false, 200);
}
}
}
<app-button
throttledClick
[isDisabled]="isButtonDisabled"
(throttledClick)="onThrottledClick()">
Click Me
</app-button>
When isButtonDisabled is true, the button is disabled, but clicking it still triggers the onThrottledClick() method. I expected that event.stopPropagation() in the button component would prevent the click event from reaching the directive, but it doesn’t.