What is the best way to do some action when the div in the template changes size? The size of the div changes when the window is resized. With Rxjs Observable/subscribe or are the some other way?
Template:
<div #eMainFrame class="main-frame">
...
</div>
Component:
@Component({
selector: 'app-box',
templateUrl: './boxponent.html',
styleUrls: ['./boxponent.css']
})
export class BoxComponent implements OnInit {
@ViewChild('eMainFrame') eMainFrame : ElementRef;
constructor(){}
ngOnInit(){
// This shows the elements current size
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
}
Updated ponent (this example detects when the window size is changed)
constructor(ngZone: NgZone) {
window.onresize = (e) => {
ngZone.run(() => {
clearTimeout(this.timerWindowResize);
this.timerWindowResize = setTimeout(this._calculateDivSize, 100);
});
}
}
_calculateDivSize(){
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
but this gives me an error:
EXCEPTION: Cannot read property 'nativeElement' of undefined
What is the best way to do some action when the div in the template changes size? The size of the div changes when the window is resized. With Rxjs Observable/subscribe or are the some other way?
Template:
<div #eMainFrame class="main-frame">
...
</div>
Component:
@Component({
selector: 'app-box',
templateUrl: './box.ponent.html',
styleUrls: ['./box.ponent.css']
})
export class BoxComponent implements OnInit {
@ViewChild('eMainFrame') eMainFrame : ElementRef;
constructor(){}
ngOnInit(){
// This shows the elements current size
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
}
Updated ponent (this example detects when the window size is changed)
constructor(ngZone: NgZone) {
window.onresize = (e) => {
ngZone.run(() => {
clearTimeout(this.timerWindowResize);
this.timerWindowResize = setTimeout(this._calculateDivSize, 100);
});
}
}
_calculateDivSize(){
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
but this gives me an error:
Share Improve this question edited Mar 16, 2017 at 14:46 user3800924 asked Mar 16, 2017 at 13:30 user3800924user3800924 4071 gold badge3 silver badges17 bronze badges 1EXCEPTION: Cannot read property 'nativeElement' of undefined
-
Have you tried
element.resize
? This might help: stackoverflow./questions/21170607/… – Rajesh Commented Mar 16, 2017 at 13:31
1 Answer
Reset to default 12The browser doesn't provide anything, therefore you need to poll the value
ngDoCheck()
is called when Angular runs change detection. I think this is a good place to do the check:
ngDoCheck() {
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
If you only need to check once after ponent creation, use
ngAfterContentInit(){
// This shows the elements current size
console.log(this.eMainFrame.nativeElement.offsetWidth);
}