【发布时间】:2018-05-27 18:30:46
【问题描述】:
想象一下: 1.在component.html中,你有
<div id = "myDiv">
<p>{{text}}</p>
<div>
<button (click)="changeText()">changeText</button>
在 component.css / 我们没有明确设置 div 的高度。 div 的高度取决于 p 元素 的高度。也就是说,p里面的字数决定了div
的高度
在 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