【问题标题】:How to get scrollWidth and offSetWidth of div which is being used as ngx-datatable-cell-template inside ngx-datatable如何获取在ngx-datatable中用作ngx-datatable-cell-template的div的scrollWidth和offSetWidth
【发布时间】:2019-07-08 22:51:22
【问题描述】:

我想获得一个子组件中的 div 的 scrollWidth 和 offSetWidth,我将子组件加载为 ngx-datatable 中的 ngx-datatable-cell-template。我总是把值设为 0

我为 div 元素添加了模板变量,并使用 ViewChild 在组件中创建了一个变量。我试图从 ngAfterViewInit 方法中获取值。 variable.nativeElement.offsetWidth 总是给 0。我在子组件中做所有这些。

有人知道为什么这总是给出 0 值吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    我做了两件事来解决这个问题

    1. 我在 ngAfterViewInit 方法中使用了 setTimeOut。我从 setTimeOut 内部读取了 UI 元素的 offsetWidth 和 scrollWidth。超时时间为 0。

    this.cmetsDiv.nativeElement.offsetWidth
    this.cmetsDiv.nativeElement.scrollWidth

    当我尝试读取 setTimeOut 之外的值时,我只得到 0。因为 ngx-DataTable 渲染仍在进行。 setTimeOut 仅在它们可用/呈现后执行语句。

    1. 当我们更新 ngx-datatable 的内容时,表只是更新了行的内容,并没有重新创建它们。

    例如,网格上已经有两行。现在我们用三个记录更新网格。该表将使用新记录更新现有的两条记录。在这种情况下,对于这些记录,底层子组件的“ngOnInit 和 ngAfterViewInit”将不会被触发。如果我们想根据新内容改变这些行的任何内容,我们需要借助“ngOnChanges 和”ngAfterViewChecked/ngAfterContentChecked”来完成。

    当我们使用 ngAfterViewChecked/ngAfterContentChecked 时,我们需要小心,因为即使我们在鼠标悬停时它们也会被触发。

    对于第三个新行,表格将创建新行,并且底层子组件将触发“ngOnInit and ngAfterViewInit”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多