In Angular, how to I get the correct coordinates of an element after routing change?

284 Views Asked by At

I have a very small basic angular (14) SPA with a couple of routes. I'm using @ViewChild to get the coordinates of a particular element:

 @ViewChild('testElement', { static: true }) testElement!: ElementRef<HTMLDivElement>;

and then

ngAfterViewInit(): void {
    var position = this.fadeInText.nativeElement.getBoundingClientRect();
    var y = position.top; // (etc)
}

What I've noticed is that I get incorrect y values if I return to the route after going to another route.

However, if I check the positions again in ngAfterViewChecked after it has fired at least once before, I get the correct position values.

Is there a better way to handle this? I can't seem to find any other documentation on this issue.

Many thanks!

1

There are 1 best solutions below

2
Drenai On

It can takes a moment for the DOM to render completely. A short setTimeout will probably work

ngAfterViewInit(): void {
    setTimeout(() => {
       this.positionCalculations()
    }, 20)
}

You could also use an RxJS timer(20) rather than setTimeout, that way you can add a takeUntil in case routes change very fast