简体   繁体   中英

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';;

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

  touchmove(event) {
    console.log(this)
  }

}

I have the button's html

{{button}}

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 touchmove is fired, this is null. If I use this.renderer.listen(this.elementRef.nativeElement, 'touchmove', this.touchmove.bind(this)) also acts a odd because the event argument is weird, sometimes it has no touches in it (which doesn't happen when I use a (touchmove)="touchmove()" 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?

Edit:

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: my-button

如果您使用箭头功能,那么this将工作

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM