lys1030
lys1030

Reputation: 283

Angular 2 How to add click event with empty template?

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

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

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

Related Questions