2017-03-16 4 views
5

テンプレートのdivのサイズが変更されたときに何らかのアクションを実行する最も良い方法は何ですか?ウィンドウのサイズを変更すると、divのサイズが変更されます。 Rxjs Observable/Subscribeや他の方法がありますか?要素のサイズが角2で変化したときの観察方法

テンプレート:

<div #eMainFrame class="main-frame"> 
    ... 
</div> 

コンポーネント:

@Component({ 
    selector: 'app-box', 
    templateUrl: './box.component.html', 
    styleUrls: ['./box.component.css'] 
}) 
export class BoxComponent implements OnInit { 
    @ViewChild('eMainFrame') eMainFrame : ElementRef; 

    constructor(){} 

    ngOnInit(){ 
    // This shows the elements current size 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
    } 
} 

更新されたコンポーネント(ウィンドウサイズが変更された場合、この例では、検出)

constructor(ngZone: NgZone) { 

    window.onresize = (e) => { 
    ngZone.run(() => { 
     clearTimeout(this.timerWindowResize); 
     this.timerWindowResize = setTimeout(this._calculateDivSize, 100); 
    }); 
    } 
} 

_calculateDivSize(){ 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
} 

が、これは私にエラーを与え:

EXCEPTION: Cannot read property 'nativeElement' of undefined

+0

使用します。私は、このチェックを行うには良い場所だと思いますか?これは役立ちます:http://stackoverflow.com/questions/21170607/angularjs-bind-to-directive-resize – Rajesh

答えて

4

ブラウザを使用すると、値に

ngDoCheck()をポーリングする必要があるので、何を提供していない角度の実行が検出を変更したときに呼び出されます。あなたが唯一のコンポーネントを作成した後に一度チェックする必要がある場合は

ngDoCheck() { 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
} 

、あなたは `element.resize`を試してみました

ngAfterContentInit(){ 
    // This shows the elements current size 
    console.log(this.eMainFrame.nativeElement.offsetWidth); 
} 
+0

ngDoCheckは動作しますが、ngDoCheck()は何度も呼び出されます。 – user3800924

+1

変更検出が実行されるたびに実行されます。あなたの正確な要件や、サイズを読むタイミングをより良くするために利用できるイベントがあるかどうかによって異なります。 –

関連する問題