【问题标题】:How to get the dimension of dynamic rendered element in Angular如何在Angular中获取动态渲染元素的尺寸
【发布时间】:2018-05-27 18:30:46
【问题描述】:

想象一下: 1.在component.html中,你有

<div id = "myDiv">
      <p>{{text}}</p>
<div>
<button (click)="changeText()">changeText</button>
  1. 在 component.css / 我们没有明确设置 div 的高度。 div 的高度取决于 p 元素 的高度。也就是说,p里面的字数决定了div

  2. 的高度
  3. 在 component.ts 中 有一个函数,我们可以随时调用它并设置 {{text}} 属性。因此 div 和 p 在运行时动态呈现。喜欢:

export class someComponent implements OnInit {

  constructor(private el: ElementRef) { }

  ngOnInit() {
  }

  changeText() {
    this.text = 'blablablabla.....';
    let divEl = this.el.nativeElement.querySelector('#myDiv');
    divEl.clientHeight/ or offsetHeight or/ getComputedStyle (can not get the correct value here!)
  }
}

问:我改变文本后如何获得div的实际高度。 (我可以通过 ElementRef 获取元素)我试过了

【问题讨论】:

  • element.offsetHeight 应该返回元素的实际高度,但可能不在内容更改的执行周期中,除非您强制进行 Angular 更改检测。请在您想要使用p 元素高度的位置显示代码和标记。
  • @ConnorsFan,问题已更新

标签: javascript html css angular


【解决方案1】:

它返回以前的值,因为浏览器需要时间来计算新样式。

RequestAnimationFrame API 是您正在寻找的。​​p>

设置新文本后,使用 RequestAnimationFrameAPI,它是在浏览器准备就绪时触发的回调,基本上是在其渲染队列为空时。

this.text = "blablablabla...."
window.requestAnimationFrame(() => {
  // access the new css values here
})

【讨论】:

    【解决方案2】:

    在大多数情况下,您不需要在代码中设置 div 容器的高度。它会自动调整其内容,并且可以使用 CSS 样式属性进行微调。

    但是如果你想对段落高度做一些特殊的计算来设置div的高度,你可以通过数据绑定来完成(在计算中使用element.offsetHeight属性):

    <div [style.height.px]="calculateDivHeight(paragraph)">
        <p #paragraph>{{text}}</p>
    <div>
    <button (click)="changeText()">changeText</button>
    
    public calculateDivHeight(paragraph: HTMLElement): number {
        return doSomeProcessing(paragraph.offsetHeight);
    }
    

    如果您在更改段落内容后强制更改检测(请参阅this answer),您当前的代码也可以工作:

    import { ApplicationRef } from '@angular/core';
    
    constructor(private applicationRef: ApplicationRef, ...) {
      ...
    }
    
    changeText() {
      this.text = 'blablablabla.....';
      this.applicationRef.tick();
      let divEl = this.el.nativeElement.querySelector('#myDiv');
      ...
    }
    

    【讨论】:

    • 其实,我确实想根据 chaning div Hieght..// 我设置 div width = 200px 进行计算(用于一些动画),例如,div 的高度将根据p 元素。 //
    • 您可以调整doSomeProcessing()以满足您的需求。
    • 此方法的一个可能缺陷是每次更改检测开始时都会调用 calculateDivHeight() 函数,这意味着每个异步函数(click、settimeout、ajax 请求)都会触发更改检测,然后触发此功能
    • 一种替代方法是使用您的原始代码并强制进行更改检测,例如使用ApplicationRef.tick()。我在答案中添加了更多细节。
    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多