Angular2-更新组件时通知指令的最佳实践是什么?



我有一个工具提示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;
  }
}

tooltipDiractive

@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>

您可以在指令中添加@Output(),以通知主机组件

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>

相关内容

  • 没有找到相关文章

最新更新