1

I made a custom button component and I am trying to make a directive that can be applied on the button in order to dynamically add some behavior when the user clicks it :

@Directive({
  selector: '[appMyDirective]'
})
export class AppMyDirective {

  // Here, I inject the button instance
  constructor(private button: MyButtonComponent) {
    this.button...what()?
  }

}

I could add some code on MyButtonComponent where I handle an array of callbacks but I would prefer to avoid that. How can I dynamically handle the click event on MyButtonComponent without modifying its code?

4
  • Do you just need a way to react on click actions within your directive? Commented Sep 10, 2018 at 16:34
  • @Nickolaus Yes, do you have a way of doing that? Commented Sep 10, 2018 at 16:38
  • @HostListener decorator is not enough here? Commented Sep 10, 2018 at 16:40
  • should be... I hope the syntax is correct but basically this is how you can listen to any event within a directive or an component Commented Sep 10, 2018 at 16:43

2 Answers 2

3

This is pretty simple, just create a function inside your directive:

 @HostListener('click', ['$event']) click(event) {
  event.preventDefault();
  ... your code
 }

see also: https://stackoverflow.com/a/34734906/1173391


also usefull:

Why use HostListener and not addEventListener on the element? Angular is smart enough to unsubscribe from the event by itself as the component/directive gets destroyed. If you use addEventListener you will to remove the binding manually otherwise the binding may persist over time.

Sign up to request clarification or add additional context in comments.

Comments

0

use ViewContainerRef like this :

@Directive({
  selector: '[appMyDirective]'
})
export class MyDirective{

  constructor(
    private viewContainerRef: ViewContainerRef
  ) { }

  ngOnInit() {
    const ele = this.viewContainerRef.element.nativeElement as Element;

    ele.addEventListener('click',e =>{ 
        console.log(e)
    });
  }

}

5 Comments

Works like a charm. I wondering is there is a more "angular-friendly" solution that does not involve getting the native element.
as @Nickolaus said its much better to use @HostListener . i didnt work with angular for a long time and forgot that solution .
avoid this, to avoid possible memory leaks
@Nickolaus may i ask why ? i think event listener doesnt destory when directive destories , right ?
yes... the eventlistener may (must not) still be existing and it can be that the memory which it preserves is not cleared until you leave the page/close the tab...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.