我有一个子组件,从其父组件接收数据并在 div 中显示文本。父母有可能undefined
作为数据发送。当它执行时,div 应该将其高度转换为 0,我通过 css 转换来实现。由于我不知道文本的长度,因此应该将 div 的高度转换为auto
. 我找到了一个这样做的代码示例,我已经将其转换为适合我的组件。
export class LanguageDetail implements OnChange, OnInit {
@Input() language: Language
@ViewChild("detailPanel") detailPanel: ElementRef;
private shownLanguage: Language;
ngOnInit() {
this.shownLanguage = new Language();
}
ngOnChange() {
if (this.detailPanel) {
var detailPanel: JQuery = $(this.detailPanel.nativeElement);
if (this.language) {
...
// calculate the end height and apply a transition with fixed values to this.shownLanguage
this.shownLanguage = this.language;
oldHeight = detailPanel.height();
detailPanel.height("auto");
newHeight = detailPanel.height();
detailPanel.height(oldHeight);
...
} else {
...
// do a transition to 0 for this.shownLanguage
...
}
}
}
}
现在的问题是,当调用 ngOnChange 时,属性语言实际上已经改变,但是视图绑定到并且在 ngOnChange 函数中分配给它this.shownLanguage
时实际上并没有更新。对自身this.language
的绑定也是如此。this.language
OnChange 事件被击中得太早了。由于 div 中缺少文本,我没有收到正确的高度,因此我的计算运行不正确。实际上是否有一个事件在视图更改时触发,或者是否有办法强制重绘视图,以便我实际上可以获得具有正确高度的 div?