Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
¿Cómo asegurarse de que ngAfterViewInit se ejecute después de que se represente un determinado elemento HTML?

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Intenta usar _elementRef en su lugar:

 this._elementRef.nativeElement.querySelector('#'+fragment)
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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 .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!