Home > Net >  changing element in ngOnInit not working when changing route, but is able to access element
changing element in ngOnInit not working when changing route, but is able to access element

Time:11-08

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.

CodePudding user response:

Try ngAfterViewInit() for changing 2 elements.

CodePudding user response:

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

  • Related