我正在尝试在模板中引用组件的元素,高度始终为0.
export class LoginComponent {
@ViewChild("loginForm", {read: ElementRef})
loginForm;
constructor() {}
ngAfterViewInit() {
console.log("form height: ", this.loginForm.nativeElement.offsetHeight);
}
click() {
console.log("form height: ", this.loginForm.nativeElement.offsetHeight);
}
}
模板
<div class="modal-content"
[style.height.px]="contentHeight">
<login-form #loginForm
(click)="click()"
[class.active]="currentForm === 'login'">
</login-form>
<register-form
[class.active]="currentForm === 'register'">
</register-form>
<div #registerSuccess class="register-success"
[class.active]="currentForm === 'registerSuccess'">
Thank you for registering
</div>
</div>
这很奇怪,因为元素渲染得很好并占用了空间,但即使在几秒钟后点击仍然会返回0的高度。
答案 0 :(得分:1)
您可以为组件设置:host { display: block }
,使其具有高度。默认值为display: inline
。如果保留默认值,则宽度和高度将为0
答案 1 :(得分:1)
我刚刚在setTimeout()
函数中添加了ngAfterViewInit()
,如下所示:
setTimeout(() => {
// Do what you want here
console.log(this.myElement.nativeElement.offsetHeight);
}, _timeout); // Mine worked even with _timeout = 1
输出不再是零了。
100%的工作方式是:
let offsetHeight = 0;
const refreshInterval = setInterval(() => {
if (offsetHeight === 0) {
offsetHeight = this.giftImage.nativeElement.offsetHeight;
// Do what you want here
console.log(this.giftImage.nativeElement.offsetHeight);
} else {
clearInterval(refreshInterval);
}
}, 10);