有没有一种方法来发射事件中指令
问题描述:
我用Angular2和拖放(在某些限定区域)写一些@Directive,想拖动时发出事件结束 - 所以当拖动到底是我调用方法endDragging。 1.这个方法的主体应该是什么样的?2.这个指令的用法应该如何(特别是如何将eventHandler设置为指令)。有没有一种方法来发射事件中指令
@Directive({
selector: '[draggable]'
})
export class Draggable {
@Input('draggable') boundary: any;
...
endDraging() {
// ??? how emit event from here?
}
}
在HTML模板(??? =如何设定为可拖动,endDragging事件处理程序):
<div [draggable]="{x_min:10, x_max:100, y_min:20, y_max:200}" ...???... >
...some content...
</div>
答
我发现了一些工作解决方案,但不幸的是有一点点脏解决办法:
假设我们有在他的模板中使用可拖动div的组件:
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
directives: [ Draggable ],
})
export class MyComponent {
myVariable = 0;
boundary() {
return {
x_min:10,
x_max:100,
y_min:20,
y_max:200,
self: this,
onDragEnd: this.onDragEnd,
};
}
onDragEnd(x,y,boundary) {
// handle drag end event, to get acces to 'this' (instance of MyComponent class use boundary.self)
boundary.self.myVariable = 1;
}
}
在模板中。 HTML我们有:
<div [draggable]="boundary()">...</div>
而且出指令将看起来像:
@Directive({
selector: '[draggable]'
})
export class Draggable {
@Input('draggable') boundary: any;
...
endDraging() {
this.boundary.onDragEnd(this.x,this.y, this.boundary);
}
}
肮脏的事情是,MyComponent.onDragEnd方法没有“这个”(!),所以访问我必须将“this”放在由“边界()”方法调用的对象中。我不知道是什么原因 - 可能是角度原因,或者可能是打字稿导致这个问题......我不知道。
什么类型的事件你想从这里发出的? –
用户停止拖动元素的事件 –