我试图获取组件的宽度,但它为0。我还尝试将代码放入ngOnChanges()。
constructor(private element: ElementRef) {
this.htmlElement = this.element.nativeElement;
let width = this.htmlElement.offsetWidth;
}
元素样式:
display: block;
position: absolute;
left: 100;
我尝试使用clientWidth(),但它也为0。如何获得角度2中的元素的宽度?
更新:
我不使用位置绝对值且宽度正确,所以我想问的问题是如何获取绝对位置元素的宽度?
尝试将代码移至AfterViewInit
生命周期挂钩方法,并使用@ViewChild()装饰器,而不是直接在中注入元素constructor
。
试试这个代码:
import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core'
@Component({
selector: 'my-app',
template: `
<div #child>
<h2>Hello!</h2>
</div>
`,
})
export class App implements AfterViewInit {
@ViewChild('child') element: any;
htmlElement: HTMLElement;
constructor() {}
ngAfterViewInit() {
this.htmlElement = this.element.nativeElement;
let width = this.element.nativeElement.offsetWidth;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句