2017-12-05 17 views
1

コンポーネントから幅を取得しようとしていますが、0です。また、ngOnChanges()にコードを入れてみました。絶対位置の要素の幅を角度で取得する方法

constructor(private element: ElementRef) { 
    this.htmlElement = this.element.nativeElement; 
    let width = this.htmlElement.offsetWidth; 
} 

要素のスタイル:

display: block; 
position: absolute; 
left: 100; 

私は(clientWidthを使用してみました)が、それはあまりにも0です。どのように角度2の要素の幅を取得できますか?

更新:

私は絶対位置を使用していないと幅が正しいので、私は、私は絶対的な位置付け要素の幅を得るのですか疑問があると仮定?使用する

+0

あなたのHTMLコードを追加しますか? – Aravind

+0

表示ブロックを含むdiv –

答えて

1

に要素に関連付けなければならないし、に直接要素を注入する代わりに@ViewChild()デコレータを使用してください。

import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core' 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div #child> 
     <h2>Hello!</h2> 
    </div> 
    `, 
}) 
export class App implements AfterViewInit { 
    @ViewChild('child') element: any; 
    htmlElement: HTMLElement; 

    constructor() {} 

    ngAfterViewInit() { 
    this.htmlElement = this.element.nativeElement; 
    let width = this.element.nativeElement.offsetWidth; 
    } 
} 

またはthe working example hereを参照してください。

は、このコードを試してみてください。また、コメントで説明を確認してください。

+0

と同じ結果0 –

+0

これは要素への参照を取得する方法に問題があるようです。要素を 'コンストラクタ'に挿入するとDOMにはまだレンダリングされません。手動で変更を検出しないので、デフォルト値の '0'のままです。代わりに[@ViewChild()](https://angular.io/api/core/ViewChild)デコレータで要素を参照してください。 [実際の例](https://plnkr.co/edit/0GIA0r0w5e7TP2DBhd1n)を参照してください。私の答えを更新できるように助けてくれたら教えてください。 –

+0

質問を更新しましたか? –

0

試してみてください。

const rect = this.element.nativeElement.getBoundingClientRect(); 
const width = rect.width; 
+0

まだ幅0の –

0

あなたはAfterViewInitライフサイクルフックメソッドにコードを移動しようelementRef

@ViewChild('foo') foo: TemplateRef; 

<div #foo> 
    <h2>Hello {{name}}</h2> 
</div> 
    {{foo.clientWidth}} 

LIVE DEMO

関連する問題