我使用@HostBinding
与Chrome的Drag and Drop API一起设置类,如下所示:
@Directive({ selector: '[sortable-article]' })
export class SortableArticleComponent {
@HostBinding('class.dragged-element')
isDraggedArticle: boolean = false;
constructor(elRef: ElementRef, private ref: ChangeDetectorRef, private appRef: ApplicationRef, private dndService: ArticleDndService) {
this.el = elRef.nativeElement;
Observable.fromEvent(this.el, 'dragstart').subscribe(e => this.onDragStart(<DragEvent> e));
Observable.fromEvent(this.el, 'drop').subscribe(e => this.onDrop(<DragEvent> e));
}
onDragStart(event: DragEvent) {
this.isDraggedArticle = true;
}
onDrop(event: DragEvent) {
event.preventDefault();
this.isDraggedArticle = false;
}
}
发生的事情是,更多次,然后,isDraggedArticle
类不会从元素中删除,我不知道为什么。我尝试添加
this.ref.detectChanges();
this.appRef.tick();
到onDrop方法(其中ref
是ChangeDetectorRef
而appRef
是ApplicationRef
),但它没有帮助。
答案 0 :(得分:1)
Ich认为我找到了问题的解决方案:drop
事件不会在已拖动的项目上触发,但会在被删除的项目上触发。这意味着我不需要在drop回调中设置this.isDraggedArticle = false
,而是需要在dragend
回调中执行此操作:
@Directive({ selector: '[sortable-article]' })
export class SortableArticleComponent {
@HostBinding('class.dragged-element')
isDraggedArticle: boolean = false;
constructor(elRef: ElementRef, private ref: ChangeDetectorRef, private appRef: ApplicationRef, private dndService: ArticleDndService) {
this.el = elRef.nativeElement;
Observable.fromEvent(this.el, 'dragstart').subscribe(e => this.onDragStart(<DragEvent> e));
Observable.fromEvent(this.el, 'dragend').subscribe(e => this.onDragEnd(<DragEvent> e));
}
onDragStart(event: DragEvent) {
this.isDraggedArticle = true;
}
onDragEnd(event: DragEvent) {
this.isDraggedArticle = false;
}
}