Akshat Akshat - 10 months ago 68
Javascript Question

Angular 2 binding an event to a component at its selector level

I have the following Angular 2 component:

import { Component, ElementRef, Renderer } from '@angular/core';;

selector: 'my-button',
templateUrl: 'button.html'
export class ButtonComponent {
private text: string;
private elementRef: ElementRef,
private renderer: Renderer
) {
this.text = 'test';

touchmove(event) {


I have the button's html


I have the component where its used in another page:

What I want to do is to bind the
<my-button (touchmove)="touchmove()">
. I can't do this though because the logic for this has to happen inside the component not outside it.

I don't really want to make a sub-element inside the button template. I've tried binding to the element using:

this.renderer.listen(this.elementRef.nativeElement, 'touchmove', this.touchmove);

The problem with the above strategy is though, when
is fired,
is null. If I use
this.renderer.listen(this.elementRef.nativeElement, 'touchmove', this.touchmove.bind(this))
also acts a odd because the
argument is weird, sometimes it has no touches in it (which doesn't happen when I use a
style binding on the component parent's page.

Is there a correct way to bind the events without using a sub element in my button template, or getting the weird binding issues i'm having?


By inside my component, I mean if I did this with my html instead of {{button}}

<div (touchmove)="touchmove()">{{text}}</div>

It solves my issue, but I can't bind to this i want to bind to the element that contains this div, the component selector itself:

Answer Source

If you use arrow function then this will work

this.renderer.listen(this.elementRef.nativeElement, 'touchmove', (e) => this.touchmove(e));