I have a directive that's at the top level of the app and queries elements via document.querySelector and hands them to fromEvent. The problem is, that when the code in the directive's ngAfterViewInit runs, the DOM isn't fully rendered yet so the element query returns null.
I could run the code in setTimeout with some arbitrary amount of time, but that doesn't seem like a sustainable, and flexible solution.
Any ideas for how this can be elegantly handled?
Right now, my code looks like some variation of this:
ngAfterViewInit() {
const trackedEl = document.querySelector('#myInput');
const input$ = fromEvent(trackedEl, 'input')
.pipe(
map((inputEvent: any) => inputEvent.target.value)
)
.subscribe((v) => {
console.log(`Got to the observable:: ${v}`, count++);
})
}
I ended up finding the solution I was looking for.
The child elements were not rendered in time likely because they were responding to some outstanding http event that hadn't yet returned a response. After reading through the documentation for change detection and ngZone, it looked like outstanding http events count as "micro tasks."
The below code is what worked for me.
ngOnInit() {
this.ngZone.onMicrotaskEmpty.pipe(take(1)).subscribe((a) => {
this.initiateElementEventListeners();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With