Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directive to stop a click not working Angular 2

Tags:

angular

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

like image 424
exk0730 Avatar asked Jul 31 '18 12:07

exk0730


1 Answers

You are getting it wrong, your code does work.

  1. What is the default action of a button with no type?? Nothing! The method under (click) call is not the default action for the browser.
  2. You are trying to stop the propagation? There is no listener to the click event above the DOM chain, There is an handler in the same element. So stop propagation is of no use.

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

like image 87
Ashish Ranjan Avatar answered Oct 19 '22 04:10

Ashish Ranjan