When using HostListener
on a click event and trying to stop the propagation of that event, the click handler on the actual element still fires.
Here's the relevant code and a stackblitz as an example.
// Directive
@Directive({
selector: '[appDirective]'
})
export class AppDirective {
@HostListener('click', ['$event']) onClick($event: Event) {
$event.preventDefault();
$event.stopPropagation();
alert('i tried to prevent this...');
}
}
// HTML
<button (click)="doSomething()" appDirective>Click Me</button>
// Click handler
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
doSomething() {
alert('I was not prevented.');
}
}
Am I doing something wrong?
https://angular-nufbqg.stackblitz.io
You are getting it wrong, your code does work.
button
with no type?? Nothing! The method under (click)
call is not the default action for the browser.You can solve your issue based on what you require. Say, you have to submit a form on the button click. Then a submit
button types default action would be to submit the form. preventDefault()
will work there.
<form (ngSubmit)="doSomething()">
<button type="submit" appDirective>Click Me</button>
</form>
export class AppDirective {
@HostListener('click', ['$event']) onClick($event: Event) {
console.log("host listener called"); // will be called
$event.preventDefault();
}
}
doSomething() {
console.log("do Something called"); // won't be called
}
https://stackblitz.com/edit/angular-kdajrk
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