简体   繁体   中英

Directive to stop a click not working Angular 2

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.

  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

export class AppDirective {
 @HostListener('mousedown', ['$event']) onClick(evt: Event): boolean {
  evt.preventDefault();
  evt.stopPropagation();
  alert('i tried to prevent this...');
  return false;
 }
}

you have to returned false

我接受了Ashish的答案,因为我在技术上做错了什么,但是现在我只是要在元素上禁用指针事件,该指令是为了获得我想要的功能(不要真的需要像形式一样的解决方法 - 提交)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM