1

私はtooltipディレクティブを持っています。tharはコンポーネントをテンプレートとして使用しています。コンポーネントを動的に作成する際、ツールチップのDOM要素はまだinnerHtmlで準備ができていません。コンポーネントは、たとえばngAfterViewInitイベントの後にのみ実際の幅を取得します。Angular2 - コンポーネントが更新されたときにディレクティブに通知するためのベストプラクティスは何ですか?

しかし、この指示文では、コンポーネントテンプレートのレンダリングが完了した時点がわかりません。コンポーネントのプライベートな議論(ディレクティブから)を見て、いつ変更/更新されるのかを知ることができますか?

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

を通知するためにあなたの指示に@Output()は、それらがhtml' –

+0

'で使用されているかのコードは、このコード'

text with tooltip on mouseOver
コンポーネントテンプレートの '一部であることを示しますか? –

+0

いいえ、これは、私がユーザにツールチップディレクティブ – AngularOne

答えて

1

あなたが追加することができますホストコンポーネント

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> 
+0

ここでの問題は、tooltipディレクティブを使用すると、ユーザーはdomReadyイベントを記述する必要もあるということですか? – AngularOne

+0

はい。親がツールチップを認識できるようにする方法を他にどのように定義しますか?他の方法もあるかもしれませんが、私はあなたの必要条件についてさらに詳しい情報が必要です。ツールチップの準備が整ったらどうなりますか? –

+0

この指示文は使い方が簡単です。私は、ディレクティブがコンポーネントテンプレートがいつ用意されているかを知る方法を探していますが、これはユーザーが気をつけなければならないものです – AngularOne

関連する問題