[英]How can I wait until something is not null then run the function
因此,當前在ngOnInit
上調用此函數highlight
,但是放入DOM
的文本ngOnInit
需要一秒鍾的時間才能寫入DOM
。
因此,當函數運行並在那兒期待文本時,它返回null
。 當document.getElementById('scrollable')
不是 === null
時,如何才能運行此函數。
到目前為止,使它運行的唯一方法是超時800ms
但這不好,因為某些人的互聯網速度比其他人慢,因此如果Internet或計算機花費較長的時間來加載頁面,則會造成問題。
我嘗試了幾種不同的方法,但是沒有一種起作用。 如果有人有什么好的建議,請隨時告訴我。
highlight(words) {
const high = document.getElementById('scrollable');
const paragraph = high.innerHTML.split(' ');
}
}
當前使用Angular 6。
HTML: https : //gist.github.com/ElAndy94/fa78b5b25a73716e2c32045c6c6be1ff
TS: https : //gist.github.com/ElAndy94/85950e0e84aad30a72d3b91faa7d6278
我建議您看一下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(' ');
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.