Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

411
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

Try ngAfterViewInit() for changing 2 elements.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda