访问 MatButton 内的 elementRef。角6
我正在尝试获取元素的边界。它与 div 配合得很好,但是当我尝试对带有角度材质指令的按钮执行相同操作时,我得到了 MatButton 对象,并且无法在其上使用 getBoundingClientRect 。我可以做我需要做的事情来获取 div 的边界,但是按钮的边界会不那么麻烦,因为它不会在应用程序的生命周期中改变大小。
模板摘录:
<div #container>
<button #button mat-flat-button>Button</button>
类摘录
@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);
}
我从日志中得到的内容
MatButton {_elementRef: ElementRef, _disableRipple: false, _disabled: false, _platform: Platform, _focusMonitor: FocusMonitor, …}
ElementRef {nativeElement: div}
当尝试在按钮行上调用 getBoundingClientRect 时,出现以下错误:
ERROR TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect')
我将不胜感激的指导
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
static
属性并将其设置为true
:Use the
static
property and set it totrue
: