I created the following directive and I'd like to prevent the (click)
event from being executed under certain conditions (or delay the click, or ask the user for confirmation, etc). For demonstrational purposes my goal below is just prevent executing the event at all:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[disabledButton]'
})
export class DisabledButtonDirective {
@HostListener('click', ['$event'])
clickEvent(event) {
event.stopImmediatePropagation();
event.preventDefault();
event.stopPropagation();
}
constructor() {
}
}
This is my markup:
<button (click)="shouldNotBeExecuted()" disabledButton>Push Me</button>
In the same above I'd like the shouldNotBeExecuted()
method not to be executed. But it is...
I created the following directive and I'd like to prevent the (click)
event from being executed under certain conditions (or delay the click, or ask the user for confirmation, etc). For demonstrational purposes my goal below is just prevent executing the event at all:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[disabledButton]'
})
export class DisabledButtonDirective {
@HostListener('click', ['$event'])
clickEvent(event) {
event.stopImmediatePropagation();
event.preventDefault();
event.stopPropagation();
}
constructor() {
}
}
This is my markup:
<button (click)="shouldNotBeExecuted()" disabledButton>Push Me</button>
In the same above I'd like the shouldNotBeExecuted()
method not to be executed. But it is...
4 Answers
Reset to default 8Yes, that's possible:
@Directive({
selector: '[disabledButton]'
})
export class DisabledButtonDirective {
subscription = new Subscription();
constructor(private elRef: ElementRef) {}
ngOnInit() {
const el = this.elRef.nativeElement;
this.subscription = fromEvent(el.parentNode, 'click', { capture: true })
.subscribe((e: any) => {
if (e.target === el) {
e.stopPropagation()
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Ng-run Example
I think, there is no problem with current code
preventDefault
- just prevent default action, e.g. for link it will direct you to another route and so on
stopPropagation
- prevent propagation through DOM tree
Some of the ways to solve this problem are set button to disabled or check, that event was preventDefaulted:
<button (click)="shouldNotBeExecuted($event)" disabledButton>Push Me</button>
@Component({
selector: "app",
templateUrl: "./app.ponent.html"
})
export class AppComponent {
shouldNotBeExecuted(event: MouseEvent): void {
if(event.defaultPrevented ) {
console.log('prevented');
}
}
}
If you make your button a ponent, you can use a different attribute for your callback so you can control when it's called.
<fancy-button (onPress)="shouldNotBeExecuted()">
Press Me
</fancy-button>
You can make use of the 'disabled' attribute to prevent click
<button (click)="shouldNotBeExecuted()" [disabled]="your condition here">Push Me</button>