我有两个命名模板。每当第一个内容发生变化时,我想将第一个高度应用到第二个高度。我可以使用组件内的 ElementRef 访问它们。因此,当我更改绑定(bind)到第一个模板的属性时,我使用相应的 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旧的高度,也就是属性改变重新渲染之前的高度。
最佳答案
使用@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);
}
}
渲染器是Renderer2,可在@angular/core
中使用关于Angular 4 - 如何将一个 div 的渲染高度应用于另一个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49356019/