I am creating a reusable component like this one:
<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>
I would like to disabled the click event when the property isDisabled is true, I tried something like that but it doesn't work.
packages/component/my-button.component.html
<button [disabled]="isDisabled" #myButton>
<ng-content></ng-content>
</button>
packages/component/my-button.component.ts
@ViewChild('uxButton') uxButton: ElementRef;
@Input() isDisabled: boolean = false;
this.myButton.nativeElement.parentNode.removeEventListener('click' , (e) => {
e.stopPropagation();
});
try like this
<button [disabled]="isDisabled" (click)="btnClick.emit($event)">
<ng-content></ng-content>
</button>
@Input() isDisabled: boolean = false;
@Output() btnClick = new EventEmitter();
Use Output
and By default the button click event won't work if button is disabled. take advantage of it
<my-button [isDisabled]="isDisabled" (btnClick)="click($event)"> submit </my-button>
It is also solved by the following CSS:
# This prevents host to get a direct click
:host {
pointer-events: none;
}
# This prevents the span inside the button to "steal" the click from the button
:host /deep/ button span {
pointer-events: none;
}
# Now only the button can get a click
# Button is the only smart enough to stop propagation when needed
button {
pointer-events: auto;
}
And now you don't to pass down the click event manually like in other answers: You have the old (click) event back :D
<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>
In your custom component, you just need to pass down the disabled property:
<button [disabled]="isDisabled" #myButton>
<ng-content></ng-content>
</button>
Also consider the stackblitz modified from another stackoverflow answer.
You can check it on (click)
attribute:
<my-button [isDisabled]="isDisabled" (click)="!isDisabled && click($event)"> submit </my-button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With