So I'm toggling a certain dom element by ngIf and right after setting it true, I'm also targetting that element by Viewchild - ElementRef. The problem is, after toggling, it takes a certain amount of time for the element to be updated in the dom and if I call in a variable holding the element, it will return as null, although after a timeout it will return the element as it got sufficient time so that the dom is updated.
Here is a sample code to understand better:
Html
<div #someElement *ngIf="showElement">
some content
</div>
Component.ts
@ViewChild('someElement') someElement:ElementRef;
toggle() {
this.showElement = true
console.log(this.someElement) //consoles undefined
}
Component.ts
@ViewChild('someElement') someElement:ElementRef;
toggle() {
this.showElement = true
setTimeout(function() {
console.log(this.someElement) //Consoles the element
}, 300)
}
Is there a way this can be done without a timeout in a proper way, like an event to check for dom update or something?