Dom Angular 2如何使用空模板添加单击事件?

Dom Angular 2如何使用空模板添加单击事件?,dom,angular,Dom,Angular,我有以下组成部分: import {Component, ElementRef} from 'angular2/core'; @Component({ selector: 'test', template: '' }) export class TestComponent { el; constructor(public elementRef: ElementRef) { this.el = elementRef.nativeElement;

我有以下组成部分:

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);
    }
}
由于模板为空,如何向组件添加单击事件?注意

this.el.addEventListener('click', this.onClick, false);

无法工作,因为单击事件被添加到this.el,而不是组件本身(控制台日志返回,而不是TestComponent本身)。

您可以使用主机侦听器:

@Component({
    selector: 'test',
    template: ''
    host: {'(click)':'clickHandler($event)'}
})
export class TestComponent {
  // @HostListener('click') // alternative way to the decorator argument
  clickHandler() {
    doSomething();
  }
}

如果你有一个空模板,你可以考虑使用一个指令。