Reputation: 95
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?
Upvotes: 6
Views: 12173
Reputation: 241
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!
Upvotes: 11
Reputation: 5972
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.
Upvotes: 1