HJ1990
HJ1990

Reputation: 415

Angular 9 - How to get width of child elements during window size change?

Is it possible to get the width of .displayItemCol when the user changes the window size? I know its possible to get the width of .displayItemCol in ngOnInit using a reference variable but is it possible to the width dynamically during window size change? I could try using the ngOnChanges() but that would detect any changes being made.

<div class="main" fxLayout="row">
  <div class="displayItemsCol" fxLayout="column">
    <app-applied-filter-bar></app-applied-filter-bar>
    <app-search-results-list></app-search-results-list>
  </div>

  <div class="displayItemCol" fxLayout="column">
    <router-outlet></router-outlet>
  </div>
</div>

I also tried the following below but that was giving me the whole window width.

<div (window:resize)="onResize($event) class="displayItemCol" fxLayout="column" >

@HostListener('window:resize', ['$event'])
onResize(event) {
  event.target.innerWidth;
}

Upvotes: 1

Views: 1103

Answers (1)

behruz
behruz

Reputation: 588

in your template HTML add #element to the div and then in your ts get the width of element like this:

@ViewChild('element', { static: true }) element: ElementRef;
@HostListener('window:resize', ['$event'])
onResize(event) {
  console.log(this.element.nativeElement.clientWidth)
}

Upvotes: 3

Related Questions