DOM / Page完全呈现后运行方法

时间:2019-03-10 12:14:02

标签: angular typescript ionic4

开发Angular 7 / Ionic 4应用程序(PWA)。我有一条指令,当内部文本发生更改时,可以自动将离子文本区域调整为正确的大小。

这很好用,下面的代码。但是,如果该页面是通过缓慢的网络连接(在Chrome DevTools-Network Slow 3G上模拟)呈现的,则文本会在组件加载时放到ion-textarea中(例如,编辑页面),但是指令AfterViewInit在DOM已完成,因此它无法记录正确的滚动高度,并且随后无法调整为正确的大小。

反正有没有检测到DOM /页面已经完成,所以我可以启动我的Adjust方法来正确设置高度吗?

我还尝试了ngAfterViewChecked并捕获了此事件的第一个实例,但同样可以在呈现DOM / Page之前触发。

任何帮助将不胜感激。

谢谢

罗伊

import { ElementRef, HostListener, Directive, AfterViewInit, Input } from '@angular/core';

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class AutoSizeDirective implements AfterViewInit {

  @Input() MaxHeight: number;
  @HostListener('input', ['$event.target'])
  @HostListener('change', ['$event.target'])

  private _pageLoaded: boolean = false;

  onInput(textArea: HTMLTextAreaElement) {
    this.adjust(textArea);
  }
  onChange(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(private element: ElementRef) {}

  ngAfterViewInit() {
    setTimeout(() => this.adjust(), 50);
  }

  adjust(textArea?: HTMLTextAreaElement) {
    textArea = textArea || this.element.nativeElement.querySelector('textarea');
    if (!textArea) {
      return;
    }

    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';

    let newHeight = textArea.scrollHeight;
    if(newHeight > this.MaxHeight){
      newHeight = this.MaxHeight;
      textArea.style.overflow = 'auto';
    }


    textArea.style.height = newHeight + 'px';
  }
}

0 个答案:

没有答案
相关问题