ViewChild ng2 设置内容在 Internet Explorer 中不起作用

ViewChild ng2 set content not working in internet explorer

我需要根据内容高度更改文本区域的高度。 按下 'Edit' 按钮时显示文本区域控件。

@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.

*.component.ts

export class MyComponent implements AfterViewInit {

   @ViewChild('text') text: ElementRef;

   ngAfterViewInit() {
      if (this.text) {
         this.text.nativeElement.style.height = (this.text.nativeElement.scrollHeight) + "px";
      }
   }
}