简体   繁体   中英

How can I wait until something is not null then run the function

So currently this function highlight gets called on the ngOnInit but the text that gets put into the DOM takes a second or so to be written into the DOM .

Therefore it is returning null when the function gets run and is expecting the text there. How can I get this function to run when document.getElementById('scrollable') does NOT === null .

The only way I have got it to run so far has been with a timeout of 800ms but that was not good because some people have slower internet than others so it would cause issues if the internet or computer takes longer to load the page.

I have tried a few different ways but none of them work. If anyone has any good advice please feel free to tell me.

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

Currently using Angular 6.

HTML: https://gist.github.com/ElAndy94/fa78b5b25a73716e2c32045c6c6be1ff

TS: https://gist.github.com/ElAndy94/85950e0e84aad30a72d3b91faa7d6278

I suggest you take a look at the Angular Component Life Cycle . You should use AfterViewInit hook to make sure your view is initialized.

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(' ');
    ...
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM