我有一个工具提示指令thar使用组件作为模板。在动态创建组件的同时,工具提示DOM元素还没有准备好使用innerHtml。该组件将获得其实际宽度,例如仅在ngAfterViewInit
事件之后。
但该指令不知道组件模板何时完成渲染。我可以观察组件的私有参数(来自指令)并知道它何时被更改/更新?
tootlipComponentTemplate
@Component({
selector: 'tooltip-container',
template: `<div #tooltipContent [innerHTML]="htmlStr"></div>`
})
export class TooltipContainer implements AfterViewInit {
@ViewChild('tooltipContent') elementRef: ElementRef;
width: number;
htmlStr: string;
constructor() {}
ngAfterViewInit() { // this is the place when I really getting the tooltip width
console.log("ngAfterViewInit: " + this.elementRef.nativeElement.offsetWidth);
this.width = this.elementRef.nativeElement.offsetWidth;
}
}
tooltipDirective
@Directive({
selector: '[myTooltip]'
})
export class myTooltipDirective {
private tooltip: ComponentRef<TooltipContainer>;
private innerHtml: string;
@HostListener("mouseenter", ['$event'])
show(event:MouseEvent): void {
// .. creating the tooltip with factory ..
console.log(this.tooltip.instance.width); // its undefined at this point !!! //
}
constructor() {}
}
HTML
<div [myTooltip]="myTextOrHtml">text with tooltip on mouseOver</div>
答案 0 :(得分:1)
You can add an @Output()
to your directive to notify the host component
export class TooltipContainer implements AfterViewInit {
@Output()
domReady:EventEmitter = new EventEmitter();
@ViewChild('tooltipContent') elementRef: ElementRef;
ngAfterViewInit() { // this is the place when I really getting the tooltip width
console.log("ngAfterViewInit: " + this.elementRef.nativeElement.offsetWidth);
this.width = this.elementRef.nativeElement.offsetWidth;
this.domReady.next(null);
}
<div [myTooltip]="myTextOrHtml" (domReady)="notifyParent()">text with tooltip on mouseOver</div>