0

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

3
  • Are you trying to call checkBoundaries in ngOnInit? The view is only ready from ngAfterViewInit onwards. Commented Feb 24, 2022 at 10:05
  • checkBoundaries are called way later, to be specific on clicking the other button in the component. Both button and container have value when calling that Commented Feb 24, 2022 at 10:20
  • If you change the type of the ViewChild for button to MatButton, you'll be able to access its properties. The "Angular" way of approaching this would be to use a directive, however. Commented Feb 24, 2022 at 10:23

1 Answer 1

0

Use the static property and set it to true:

@ViewChild('button' , {read: ElementRef, static: true}) private button : ElementRef;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.