I am trying to call this highlight()
on the ngOnInit
but I am getting this error: ERROR TypeError: Cannot read property 'innerHTML' of null
.
In the ngOninit
I have
this.annotationSub = this.annotationService
.getWordUpdateListenerTwo()
.subscribe((theHardWords: ComplexWord[]) => {
this.thewords = [];
this.theHardWords = theHardWords;
this.theHardWords.map(word => {
this.thewords.push(word.word);
this.wordWithAnnotation.push(word);
});
});
this.postsSub = this.postsService
.getPostUpdateListenerTwo()
.subscribe((posts: Post[]) => {
this.posts = posts;
this.posts.map(post => {
if (post.id === this.id) {
this.postIWant = post.fileText;
}
});
});
this.highlight(this.thewords);
This picks out the post which then gets displayed shown below:
My HTML:
<div id="scrollable">
{{ postIWant }}
</div>
This is the highlight
function which is giving me the problems, If I call this highlight
function after the document has loaded with a button it works fine, but If I call it in the ngOnInit
it does not give enough time for the innerHTML to get populated therefore throws an error.
I have tried using ngAfterViewInit(): void {}
but still even that does not give it enough time. Below is the highlight
function.
highlight(words) {
const high = document.getElementById('scrollable');
const paragraph = high.innerHTML.split(' ');
const res = [];
paragraph.map(word => {
let t = word;
if (words.indexOf(word) > -1) {
t =
'<a class="clickable" style="background-color: yellow; text-decoration: underline;">' +
word +
'</a>';
}
res.push(t);
});
high.innerHTML = res.join(' ');
const elementsToMakeClickable = document.getElementsByClassName(
'clickable'
);
const elementsToMakeClickableArray = Array.from(elementsToMakeClickable);
elementsToMakeClickableArray.map(element => {
element.addEventListener('click', this.viewAnnotation.bind(this));
});
document.getElementById('btnHighLight').style.visibility = 'visible';
}
As mentioned earlier, it works if I load the page up and press a button to trigger the highlight()
but I want it to run that function and highlight the words without me having to click anything. Does anyone have any ideas? Thanks!
(I am using Angular).