Search code examples
htmlangulargetelementbyid

How would you set getElementById when retrieving data from a different angular component?


I am working in Angular 6. I am trying to basically print a JS variable. The trouble is that the variable is created in one component but I am trying to print it in another.

What I did was create a service that would share that varaible with the new component. I then try to use getElementById to set the html id.

My more-information.html looks like:

<br>
<div>
   <div>
      <h2>User <span id="user"></span></h2>

</div>

I have a results component that does this:

this._informationServ.saveData(userArray);
this._informationServ.saveUser(user);

My information service does this:

export class InformationService {
  ourUser: string;
  userData = [];
  constructor() { }

saveUser(user){
  this.ourUser = user;
}

saveData(someArray){
  this.userData = someArray;
}

getUser(){
  return this.ourUser;
}

getData(){
  return this.userData;
}
}

And then finally I have a MoreInformation componenent that looks like:

export class MoreInformationComponent {
  finalData = [];
  ourUser: string;
  constructor(private _informationServ: InformationService) {  
    this.finalData = this._informationServ.getData();
    this.ourUser = this._informationServ.getUser();
  }

  ngOnInit() {
  }

}

I have tried using the line

document.getElementById("user").innerHTML = this.ourUser;

in the constructor of the MoreInformation Comp., which gave me the error:

TypeError: Unable to set property 'innerHTML' of undefined or null reference

I then tried creating a function onCall() inside the MoreInformation Comp. that does the getElementbyId line and call it in the constructor, which also did not work.

I also just tried doing something like

<br>
<div>
   <div>
      <h2>User {{ourUSer}}</h2>

</div>

But only User showed up Would anyone have an idea on how to best do this?


Solution

  • Instead of setting the value like this:

    document.getElementById("user").innerHTML = this.ourUser;
    

    You can declare a variable in the component where you want to render the value and set it to this.ourUser value:

    yourVariable = this.ourUser;
    

    And then use it to show the value in your template:

    <h2>User <span id="user">{{ yourVariable }}</span></h2>