我正在使用Angular Material CDK覆盖编写工具提示指令。我正在尝试将其放置在origin元素(指令收到的ElementRef)之前的左侧。
我已经将其放置在上方或右侧,但是一旦将“ overlayX”设置为“ end”,我的指令就不再呈现。
下面是我的指令代码。有人可以告诉我我的错误在哪里吗?该应用程序不会引发任何错误...
@Directive({
selector: '[tooltip]',
})
export class ShTooltipDirective implements AfterViewInit {
private overlayRef: OverlayRef;
private portal: ComponentPortal<TooltipComponent>;
private tooltipComponent: ComponentRef<TooltipComponent>;
private HOST_OFFSET = 10;
@Input('tooltip') tooltip: string | TemplateRef<any>;
@HostListener('mouseenter')
show() {
this.portal = new ComponentPortal(TooltipComponent);
this.tooltipComponent = this.overlayRef.attach(this.portal);
this.tooltipComponent.instance.content = this.tooltip;
}
@HostListener('mouseout')
hide() {
this.overlayRef.detach();
}
constructor(
private overlay: Overlay,
private elementRef: ElementRef,
) {}
ngAfterViewInit() {
const positionStrategy = this.getPositionStrategy();
const scrollStrategy = this.getScrollStrategy();
this.overlayRef = this.overlay.create({
scrollStrategy,
positionStrategy
});
}
getScrollStrategy(): any {
return this.overlay.scrollStrategies.reposition();
}
private getPositionStrategy() {
const strategy = this.overlay.position()
.flexibleConnectedTo(this.elementRef)
.withLockedPosition(false)
.withFlexibleDimensions(true)
.withPositions([
{
originX: 'start',
originY: 'center',
overlayX: 'end',
overlayY: 'center',
offsetX: this.HOST_OFFSET
},
]);
strategy.positionChanges.subscribe(change => {
const classname = this.getPositionClass(change.connectionPair);
this.setTooltipClass(classname);
});
return strategy;
}
private getPositionClass(position: ConnectionPositionPair) {
switch (position.originX) {
case 'center':
return 'tooltip__on-top';
case 'end':
return 'tooltip__after';
case 'start':
return 'tooltip__before';
}
}
private setTooltipClass(classname: string) {
if (
this.tooltipComponent &&
this.tooltipComponent.location.nativeElement
) {
this.tooltipComponent.location.nativeElement.className = classname;
}
}
}