角2结合的事件到组件

问题描述:

我有以下角2成分:角2结合的事件到组件

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) 
    } 

} 

我有按钮的HTML

{{button}} 

我有其中其中使用的成分另一页:

我想要做的是绑定<my-button (touchmove)="touchmove()">。我不能这样做,因为这个逻辑必须发生在组件内部而不是外部。

我真的不想在按钮模板中创建一个子元素。我试着结合使用元素:

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

上述策略的问题是,虽然,当touchmove被激发,this为空。如果我使用this.renderer.listen(this.elementRef.nativeElement, 'touchmove', this.touchmove.bind(this))还充当一个奇怪的,因为event说法是怪异,它也有它没有触摸(当我使用(touchmove)="touchmove()"风格组件父页面上结合这不会发生。

是否有正确的方法绑定的事件,而在我的按钮模板使用一个子元素,或者让我遇到了奇怪的绑定问题

编辑:

通过我的组件里面,我的意思是,如果我这样做我的HTML代替{{button}}

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

它解决了我的问题,但我不能绑定到这个我要绑定包含这个div,组件选择本身的元素:my-button

+0

我不明白问题所在。这是关于什么“我不能这样做,因为这个逻辑必须发生在组件内部,而不是在它之外。”里面是什么?什么是外面? –

+0

@GünterZöchbauer,我编辑更清晰。我也尝试过使用bind,但事件有时是错误的,就像touchmove在事件参数的touches属性中没有任何内容。这在我编辑中使用代码时不会发生,问题是我无法使用子元素。 – Akshat

+0

使用箭头功能帮助我btw(谢谢!),它解决了这个问题:) – Akshat

如果您使用箭头功能则this将工作

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