Reputation: 283
I have the following Component:
import {Component, ElementRef} from 'angular2/core';
@Component({
selector: 'test',
template: ''
})
export class TestComponent {
el;
constructor(public elementRef: ElementRef) {
this.el = elementRef.nativeElement;
this.renderer = new THREE.WebGLRenderer();
this.el.appendChild(this.renderer.domElement);
}
onClick() {
console.log(this);
}
}
Since the template is empty, how can I add a click event to the component? Note that
this.el.addEventListener('click', this.onClick, false);
won't work because the click event is added to this.el, instead of the component itself (console log returns < test >< /test > rather than TestComponent itself).
Upvotes: 1
Views: 2247
Reputation: 657676
You can use host-listener:
@Component({
selector: 'test',
template: ''
host: {'(click)':'clickHandler($event)'}
})
export class TestComponent {
// @HostListener('click') // alternative way to the decorator argument
clickHandler() {
doSomething();
}
}
Upvotes: 1