我需要根据内容高度更改文本区域高度。按下“编辑”按钮时会显示textarea控件。
@ViewChild
无法识别该元素,因为在组件初始化时它不存在于DOM中。
使用set content
解决了这个问题,但它只适用于chrome。 Internet Explorer不支持它。
我的代码:
<ng-containter *ngIf="isEdit">
<textarea #text formControlName="text"></textArea>
</ng-Containter>
. . .
private text:ElementRef
@ViewChild('text') set content(content:ElementRef){
this.text = content;
if (this.text){
this.text.nativeElement.style.height = (this.text.nativeElement.scrollHeight) + "px";
}
}
有解决方案吗
最简单的解决方案是使用生命周期钩ngAfterViewInit
。它被称为一旦组件完成渲染html模板,但只有一次。 Here you can read more。
export class MyComponent implements AfterViewInit {
@ViewChild('text') text: ElementRef;
ngAfterViewInit() {
if (this.text) {
this.text.nativeElement.style.height = (this.text.nativeElement.scrollHeight) + "px";
}
}
}