gpt4 book ai didi

angular - 我可以用其他鼠标事件运行@HoSTListner 吗?

转载 作者:太空狗 更新时间:2023-10-29 17:59:09 24 4
gpt4 key购买 nike

为了避免设置无用的监听器,我想仅在运行mousedown 事件 时启动mousemove 监听器。类似的东西:

在我的 component.ts 中

private startMouseMove(start: boolean){
if(start){
@HostListener('mousemove', ['$event'])
onMouseMove(event: MouseEvent){
console.log("start mousemove");
this.mousemove.emit(event);
}
}
}

@HostListener('mouseup', ['$event'])
onMouseup(event: MouseEvent){
console.log(event.type);
this.startMouseMove(false);
}

@HostListener('mousedown', ['$event'])
onMousedown(event: MouseEvent) {
console.log(event.type);
this.startMouseMove(true);
return false; // Call preventDefault() on the event
}

那当然行不通。我想知道在 Angular 中是否可行,如果可行,该怎么做?

最佳答案

一种可能的解决方案是使用响应式(Reactive)方法:

import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/takeUntil';

@Directive({
selector: '[my-drag]'
})
export class DragDirective {
subscription: Subscription;

constructor(private elRef: ElementRef, private zone: NgZone) {}

ngOnInit() {
this.zone.runOutsideAngular(() => this.initDragEvent());
}

initDragEvent() {
const el = this.elRef.nativeElement;
const mousedown = Observable.fromEvent(el, 'mousedown');
const mouseup = Observable.fromEvent(el, 'mouseup');
const mousemove = Observable.fromEvent(document, 'mousemove');
const mousedrag = mousedown.flatMap((md: any) => {
const startX = md.offsetX;
const startY = md.offsetY;

return mousemove.map((e: any) => {
e.preventDefault();
return {
left: e.clientX - startX,
top: e.clientY - startY
};
}).takeUntil(mouseup);
});

this.subscription = mousedrag.subscribe((pos) => {
console.log('mousemove is fired');
el.style.top = pos.top + 'px';
el.style.left = pos.left + 'px';
});
}

ngOnDestroy() {
if(this.subscription) {
this.subscription.unsubscribe();
}
}
}

我在 Angular 区域外运行 initDragEvent,因为我不希望发生冗余变化检测。

另一种解决方案是使用渲染器

export class DragDirective {
listener: Function;

@HostListener('mouseup', ['$event'])
onMouseup(event: MouseEvent) {
console.log(event.type);
this.startMouseMove(false);
}

@HostListener('mousedown', ['$event'])
onMousedown(event: MouseEvent) {
console.log(event.type);
this.startMouseMove(true);
return false;
}

constructor(private renderer: Renderer2) {}

private startMouseMove(start: boolean) {
this.ngOnDestroy();
if (start) {
this.listener = this.renderer.listen(document, 'mousemove', () => {
console.log("start mousemove", this.listener);
})
}
}

ngOnDestroy() {
if(this.listener) {
this.listener();
}
}
}

Plunker Example

关于angular - 我可以用其他鼠标事件运行@HoSTListner 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44156672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com