Angular 2未检测到@HostBinding的更改

时间:2017-04-21 15:46:22

标签: javascript angularjs events drag-and-drop

我使用@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方法(其中refChangeDetectorRefappRefApplicationRef),但它没有帮助。

1 个答案:

答案 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;
    }
}