How to observe when element size changes in Angular 2

What is the best way to do some things when the div in the template resizes? The size of the div changes when the window is resized. With Rxjs Watched / Subscribed or other ways?

Template:

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

component:

 @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); } } 

Updated component (this example determines when the window resizes)

 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: Unable to read property "nativeElement" from undefined

+5
source share
1 answer

The browser does not provide anything, so you need to poll the value

ngDoCheck() is called when Angular triggers change detection. I think this is a good place to check:

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

If you need to check once after creating the component, use

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

Source: https://habr.com/ru/post/1265552/


All Articles