Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31283

Add click event on Component

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?

Upvotes: 1

Views: 2429

Answers (2)

Nickolaus
Nickolaus

Reputation: 4835

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.

Upvotes: 3

SoroushNeshat
SoroushNeshat

Reputation: 674

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)
    });
  }

}

Upvotes: 0

Related Questions