【发布时间】:2016-11-13 02:01:33
【问题描述】:
我有以下 Angular 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
【问题讨论】:
-
我不明白问题出在哪里。这是什么“我不能这样做,因为逻辑必须发生在组件内部而不是外部。”里面是什么?外面是什么?
-
@GünterZöchbauer,我编辑得更清楚了。我也尝试使用绑定,但事件有时是错误的,比如 touchmove 在事件参数的 touches 属性中没有任何内容。当我在编辑中使用代码时不会发生这种情况,问题是我不能使用子元素。
-
使用箭头函数帮助我顺便说一句(谢谢!),它解决了这个问题:)
-
很奇怪。我确信arrow和
.bind(this)也会这样做。 -
我也不确定原因,或者触摸是空的但不是子元素的原因。
标签: javascript angular