Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

416
Vistas
changing element in ngOnInit not working when changing route, but is able to access element

I have an angular project with a router. In the ngOnInits for the components I want to dynamically set a a p tags value, and an img tags href. It works on inital load, but when i change routes the values dont change. The ngOnInit function is called, but the editing of the two elements does not work.

document.getElementById('discord-tag').innerHTML = username;
document.getElementById('profilePicture').setAttribute('src', image_url)

my code is simple.

i know the ngOnInit function is working because i put some console.log statements in there to test and they run each time i click on a route link.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In Angular we work with variables, manipulating the DOM directly should be the last resort, if there is no other way... BUT, usually there is an "Angular way" to handle things so that you don't need to manipulate the DOM directly. That being said, have variables in your component, which you bind to the template, so, however you get those values, assign them to variable, in OnInit, or the proper place you have them...

image_url!: string;
username!: string;

ngOnInit() {
  // doing stuff, getting the values... then:
  this.username = 'valueHere';
  this.image_url = 'valueHere';
}

Then in template use these:

<img [src]="image_url" />

<p>{{username}}</p>

As mentioned in comment, these are basic things, so I really urge you to look into the tutorial on angular.io. It's a good tutorial and you will surely learn the basics there :) https://angular.io/tutorial

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try ngAfterViewInit() for changing 2 elements.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda