我需要在运行时获取角度组件中css类的宽度
<div class="document-section"></div>
我似乎无法通过尝试其中任何一个来获得它:
$('.document-section').width()
$('.document-section').attr('width')
有错误
未捕获的TypeError:$(...)。width不是函数 at:1:22
任何人都可以帮我吗? 谢谢
答案 0 :(得分:1)
要在运行时获取类的宽度,首先需要确保在视图中绘制/渲染它。
因此,获取宽度的代码应该包含在ngAfterViewInit()
生命周期钩子中。
你没有特别需要从css类中获取它只需在div中使用ViewChild
并获得它的宽度。
<强> HTML 强>
<div #documentSection class="document-section"></div>
<强> TS 强>
@ViewChild("documentSection")
private documentSection: ElementRef;
private divWidth: number;
public ngAfterViewInit(): void {
this.divWidth = this.documentSection.nativeElement.offsetWidth;
}