【问题标题】:Angular 4 - How to apply the rendered height of a div to another div?Angular 4 - 如何将 div 的渲染高度应用到另一个 div?
【发布时间】:2018-08-27 14:28:25
【问题描述】:

我有两个命名模板。每当第一个的内容发生变化时,我想将第一个的高度应用于第二个。我可以使用组件内的 ElementRef 访问它们。因此,当我更改绑定到第一个模板的属性时,我使用相应的 ElementRef 来获取它的高度并将其应用于第二个模板的 ElementRef。

现在,问题是,在属性更改后,我从第一个模板对应的 ElementRef 得到的高度不是更新后的高度。它返回属性更改和重新渲染之前 div 的高度。

我希望能够在 div 更新后获得实际呈现的高度。我做错了什么?

更新:

代码:

var height = `${this.profile.nativeElement.offsetHeight}px`;
this.renderer.setStyle(this.board.nativeElement, "height", height);
this.renderer.setStyle(
this.board.nativeElement,
"overflow-y",
"scroll"
);

这里profile是第一个div对应的ElementRef,board是第二个div对应的ElementRef。属性更改后,我调用包含上述代码的函数。那么我得到的高度就是div的旧高度,也就是属性改变和重新渲染之前的高度。

【问题讨论】:

  • 试过element.offsetHeight; ?
  • 是的。我可以设置高度和一切。问题是 div 重新渲染后我没有得到更新的高度。
  • @NimishDavidMathew:检查 $apply 。可能是您缺少摘要周期,因此您没有获得更新的值
  • @ShashankVivek 你能详细说明如何使用 $apply 吗?我正在使用 Angular 4。
  • @NimishDavidMathew:你有错误的标签“angularjs”。您能否分享您的 Angular 4 代码,以便我们查看实际代码。尝试tick()函数进行更改检测周期。

标签: angular elementref


【解决方案1】:

使用@ViewChild访问每个div对应的ElementRef:

@ViewChild("profile") profile;
@ViewChild("board") board;

实现 AfterViewChecked 并在 ngAfterViewChecked 中执行以下操作:

constructor(private renderer: Renderer2) { 
}

ngAfterViewChecked() {
  if (this.profile && this.board) {
    var height = `${this.profile.nativeElement.offsetHeight}px`;
    this.renderer.setStyle(this.board.nativeElement, "height", height);
  }
}

rendererRenderer2@angular/core

中可用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多