3

I have a component which is manually resized so I've added a listener:

@HostListener('window:resize')
  public detectResize(): void {
    // get height and width of the component
    this.theHeight = // the coponent height
    this.theWidth = // the coponent height
  }

 theHeight = '';
 theWidth = '';

How can I get the Height and Width of the component?

teumec
  • 65
  • 1
  • 6

2 Answers2

8

Your code is listening to the window object, so you can only get the window innerHeight and innerWidth. There are 2 solutions to get the current window height.

Get the Window Sizes
Angular window resize event
Eventbinding:

<div (window:resize)="onResizeHandler($event)">...</div>
public onResizeHandler(event): void {
   event.target.innerWidth;
   event.target.innerHeight;
}

Host Listener Decorator: (The much cleaner approach!)

@HostListener('window:resize', ['$event'])
onResizeHandler(event: Event): void {
   event.target.innerWidth;
   event.target.innerHeight;
}

Component Sizes:
There are some ways to get the component size but this is a really inefficient solution!!!!! Be careful while using this. The underlying NativeElement Api will directly access the DOM! https://angular.io/api/core/ElementRef

EDIT:
To be clear, reading the element with this solution will be fine. If you need to manipulate your element be sure to use Renderer2 https://angular.io/api/core/Renderer2

// Inject a element reference into your component constuctor
...
constructor(private elementRef: ElementRef) {...}

// implement a listener on window:resize and attach the resize handler to it
public onResizeHandler(): void {
    this.elementRef.nativeElement.offsetHeight
    this.elementRef.nativeElement.offsetWidth

}

If you only want to change styling on resize events Be sure to use @media Queries in your css/scss. This will be the best way to do so!

TMFLGR
  • 213
  • 4
  • 11
  • 2
    good solution. with regard to your last solution; direct access in order to just read DOM elements should be fine unless he's manipulating them in which case the correct approach would be using `Renderer2` https://angular.io/api/core/Renderer2 – Rogelio Dec 17 '20 at 00:07
  • 2
    yes, reading is ok, whilst manipulation should not be done using the native element! i'll add this in my solution. – TMFLGR Dec 17 '20 at 13:43
1

You need to write your own code to detect the element size changes. Or you can use a library - personally, I recommend this:

https://www.npmjs.com/package/angular-resize-event

It works like a charm.

critrange
  • 5,652
  • 2
  • 16
  • 47