首页 > 解决方案 > 我怎样才能等到某些东西不为空然后运行该函数

问题描述

所以目前这个函数highlight被调用,ngOnInit但是被放入的文本DOM需要一秒钟左右的时间才能写入DOM.

因此,null当函数运行时它会返回并期待那里的文本。我怎样才能让这个函数在document.getElementById('scrollable')NOT === null运行。

到目前为止,我让它运行的唯一方法是超时,800ms但这并不好,因为有些人的互联网速度比其他人慢,所以如果互联网或计算机需要更长的时间来加载页面,就会导致问题。

我尝试了几种不同的方法,但都没有奏效。如果有人有任何好的建议,请随时告诉我。

highlight(words) {
      const high = document.getElementById('scrollable');
      const paragraph = high.innerHTML.split(' ');
   }
}

目前使用 Angular 6。

HTML:https ://gist.github.com/ElAndy94/fa78b5b25​​a73716e2c32045c6c6be1ff

技术支持:https ://gist.github.com/ElAndy94/85950e0e84aad30a72d3b91faa7d6278

标签: javascripthtmlangulartypescript

解决方案


我建议你看看Angular Component Life Cycle。您应该使用AfterViewInit钩子来确保您的视图已初始化。

import { Component, AfterViewInit } from '@angular/core';

@Component({...})
export class MyOwnComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() { // Here your view is checked and initialized.
    this.highlight();
  }

  highlight(words) {
    const high = document.getElementById('scrollable');
    const paragraph = high.innerHTML.split(' ');
    ...
  }

}

推荐阅读