I'm trying to get boundaries of an element. It works well with div, however when I'm trying to do the same with button with angular material directive I'm getting the MatButton object and I can't use getBoundingClientRect on it. I can do what I need to do with getting the boundaries of div, but it would be less cumbersome with boundaries of button, because it doesn't change size in lifetime of application.
Excerpt from template:
<div #container>
<button #button mat-flat-button>Button</button>
Excerpt from class
@ViewChild('button') button : ElementRef;
@ViewChild('container') container : ElementRef;
checkBoundaries():void [
const buttonRect = this.button.nativeElement.getBoundingClientRect();
const containerRect = this.container.nativeElement.getBoundingClientRect();
console.log(button);
console.log(container);
}
What I get from logs
MatButton {_elementRef: ElementRef, _disableRipple: false, _disabled: false, _platform: Platform, _focusMonitor: FocusMonitor, …}
ElementRef {nativeElement: div}
When trying to call getBoundingClientRect on button line I get the following error:
ERROR TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect')
I would appreciate the guidance
checkBoundariesinngOnInit? The view is only ready fromngAfterViewInitonwards.checkBoundariesare called way later, to be specific on clicking the other button in the component. Both button and container have value when calling thatbuttontoMatButton, you'll be able to access its properties. The "Angular" way of approaching this would be to use a directive, however.