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

409
Views
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 answers
Answer question

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 Report

0

Try ngAfterViewInit() for changing 2 elements.

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!