En HTML, hay un <a> que redirige a otro componente y luego se desplaza a un determinado ancla.
En el componente de destino, tengo el siguiente código
ngAfterViewInit(): void { this.route.fragment.subscribe(fragment => { const elmntLoc: HTMLElement = document.getElementById(fragment); window.scroll({ top: elmntLoc.offsetTop, behavior: "smooth" }); }); } Sin embargo, encontré que document.getElementById(fragment); siempre es null , porque este elemento se muestra condicionalmente usando ngIf = booleanVariable , y cuando se ejecuta este enlace de ciclo de vida ngAfterViewInit , esta booleanVariable aún no se calcula.
Me pregunto cómo asegurarme de que ngAfterViewInit se ejecute después de que se calcule booleanVariable y, por lo tanto, se represente este elemento.
Intenté usar setTime pero parece extraño...
¡Gracias por adelantado!
Intenta usar _elementRef en su lugar:
this._elementRef.nativeElement.querySelector('#'+fragment)Puede intentar esperar el siguiente cuadro de animación para dar la oportunidad de que se procese el elemento html.
ngAfterViewInit(): void { this.route.fragment.subscribe(fragment => { window.requestAnimationFrame(_ => { const elmntLoc: HTMLElement = document.getElementById(fragment); window.scroll({ top: elmntLoc.offsetTop, behavior: "smooth" }); } }); }Necesito ver más de su código para dar una respuesta más sólida.
Gracias por las respuestas, pero me temo que no funcionan correctamente... (Tal vez las probé de manera incorrecta).
Logré resolver este problema usando
@ViewChild('elementId') set elementName(elementName: ElementRef) { # code to scroll to a certain section of the page. }; El método se ejecutará después de que se represente este ViewChild .