I'm creating an Angular component that wraps a native <button>
element with some additional features. Buttons do not fire a click event if they're disabled and I want to replicate the same functionality. i.e., given:
<my-button (click)="onClick()" [isDisabled]="true">Save</my-button>
Is there a way for my-button
to prevent onClick()
from getting called?
In Angular you can listen to the host click event this way, and stop propagation of the event:
//Inside my-button component
@HostListener('click', ['$event'])
onHostClick(event: MouseEvent) {
event.stopPropagation();
}
This prevents the event from bubbling to ancestor elements, but it does not stop the built-in (click)
output from firing on the same host element.
Is there a way to accomplish this?
Edit 1: the way I'm solving this now is by using a different output called "onClick", and consumers have to know to use "onClick" instead of "click". It's not ideal.
Edit 2: Click events that originate on the <button>
element are successfully stopped. But if you put elements inside the button tag as I have, click events on those targets do propagate up to the host. Hm, it should be possible to wrap the button in another element which stops propagation...