【问题标题】:get width of css class in angular at run time在运行时以角度获取 css 类的宽度
【发布时间】:2017-10-17 18:56:17
【问题描述】:

我需要在运行时在我的角度组件中获取 css 类的宽度

<div class="document-section"></div>

我似乎无法通过尝试以下任何方法来获得它:

$('.document-section').width()
$('.document-section').attr('width')

有错误

未捕获的类型错误:$(...).width 不是函数 在:1:22

谁能帮我解决这个问题? 谢谢

【问题讨论】:

  • 试试这个代码 $('.document-section').css('width', '200px');
  • 你使用的是什么 Angular 版本?
  • 我没有设置宽度以使用 .css('width', '200px') 即使我尝试了 $('.document-section').css('width') 和相同的错误以上
  • @Gezzasa 角度 4

标签: html css angular width


【解决方案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;
}

【讨论】:

  • 你能帮我更多关于 div 中的 ViewChild 吗?
  • 添加了一个小例子
猜你喜欢
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-10
  • 2012-04-27
  • 1970-01-01
  • 2019-01-07
  • 2012-08-11
  • 2019-11-22
相关资源
最近更新 更多