Angular 2抽象指令需要装饰器

时间:2018-02-10 22:42:02

标签: angular

我想实现一个Angular 2指令层次结构。基类抽象类为鼠标事件设置处理程序,并将光标位置处理为具体的派生类,该类对模型进行特定处理。我有一个抽象类

export abstract class DragDirective implements AfterViewInit, OnDestroy {
    constructor(protected elementRef: ElementRef) { }
    @Input() dragTarget: Draggable;
    ngAfterViewInit() {
        // various rxjs Observables and subscription handlers for mouseevents, including ...
        ...  this.handlePoint(point);
        ...
    }
    abstract handlePoint(point: Point): void;
}

具体指示:

@Directive({
    selector: '[drag-anywhere]'
})
export class DragAnywhereDirective extends DragDirective {
    handlePoint(point: Point): void {
        this.dragTarget.setPosition(point);
    }
}

在运行时我收到错误:     无法解析DragAnywhereDirective的所有参数:(?)。 除非我还用以下内容装饰抽象类:

@Directive({
    selector: '[unusable-because-its-not-concrete]'
})

为什么有必要装饰抽象类?

1 个答案:

答案 0 :(得分:1)

您需要将elementRef传递给基类中的构造函数,如此

@Directive({
   selector: '[drag-anywhere]'
})
export class DragAnywhereDirective extends DragDirective {
   constructor(protected elementRef: ElementRef) {
       super(elementRef);
   }

   handlePoint(point: any): void {
       this.dragTarget.setPosition(point);
   }
}

有关装饰器的更多详细信息,请查看Todd Motto的blog post