2016-07-18 6 views
0

を変更したとき、私はこのようになりますHTML要素を持っていても同じ値を返す:角度2 - ElementRef.nativeElement.offSetwidthプロパティが

mysizeはH1のフォントサイズを制御する可変である
<h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1> 

タグ。 h1要素の幅は、コンテンツのフォントサイズによって決まります。

私は、私は次のコードを実行した場合、私は次のような結果に

console.log(this.titleTextElement.nativeElement.offsetWidth); 
    // returns 632px, which is the correct width. 
    this.mysize *= 0.9; 
    console.log(this.titleTextElement.nativeElement.offsetWidth); 
    // returns 632px, but the new width is 572px. 

を取得

@ViewChild('titleText') titleTextElement; 

とH1タグへの参照を取得しています、これは動作しない理由を誰も説明できますか?更新されたoffSetwidth値をどのように得ることができるかを誰かが示すことができたら、私は感謝します。

答えて

4

変更検出が実行された場合にのみビューが更新されます。

constructor(private cdRef:ChangeDetectorRef) {} 
    ... 

    console.log(this.titleTextElement.nativeElement.offsetWidth); 
    // returns 632px, which is the correct width. 
    this.mysize *= 0.9; 
    this.cdRef.detectChanges(); 
    console.log(this.titleTextElement.nativeElement.offsetWidth); 
    // returns 632px, but the new width is 572px. 

期待通りに動作するはずアリ:

あなたは次のように手動で変更検出を呼び出すことができます。

+0

チャームのような作品です!本当にありがとう! –