在 运行 时间 angular 中获取 css class 的宽度
get width of css class in angular at run time
我需要在 运行 时间 运行 获取我的 angular 组件中 css class 的宽度
<div class="document-section"></div>
我似乎无法通过尝试以下任何一种来获得它:
$('.document-section').width()
$('.document-section').attr('width')
有错误
Uncaught TypeError: $(...).width is not a function
at :1:22
谁能帮我解决这个问题?
谢谢
要在运行时获取 class 的宽度,您需要首先确保它在视图中为 drawn/rendered。
因此,无论您使用什么代码来获取宽度,都应包含在 ngAfterViewInit()
生命周期挂钩中。
您不需要特别从 css class 获取它,只需在 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;
}
我需要在 运行 时间 运行 获取我的 angular 组件中 css class 的宽度
<div class="document-section"></div>
我似乎无法通过尝试以下任何一种来获得它:
$('.document-section').width()
$('.document-section').attr('width')
有错误
Uncaught TypeError: $(...).width is not a function at :1:22
谁能帮我解决这个问题? 谢谢
要在运行时获取 class 的宽度,您需要首先确保它在视图中为 drawn/rendered。
因此,无论您使用什么代码来获取宽度,都应包含在 ngAfterViewInit()
生命周期挂钩中。
您不需要特别从 css class 获取它,只需在 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;
}