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

问题描述 投票:0回答:1

我需要根据内容高度更改文本区域高度。按下“编辑”按钮时会显示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";
   }
}

有解决方案吗

angular angular2-template
1个回答
1
投票

最简单的解决方案是使用生命周期钩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";
      }
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.