从不同的 angular 组件检索数据时如何设置 getElementById?

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

我在 Angular 6 工作。我正在尝试打印一个 JS 变量。问题是变量是在一个组件中创建的,但我试图在另一个组件中打印它。

我所做的是创建一个与新组件共享该变量的服务。然后我尝试使用 getElementById 来设置 html id。

我的更多-information.html 看起来像:

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

</div>

我有一个执行此操作的结果组件:

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

我的信息服务是这样做的:

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;
}
}

最后我有一个 MoreInformation 组件,如下所示:

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

  ngOnInit() {
  }

}

我试过使用

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

在 MoreInformation Comp. 的构造函数中,它给了我错误:

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

然后我尝试在 MoreInformation Comp 中创建一个函数 onCall()。那行 getElementbyId 行并在构造函数中调用它,这也没有用。

我也试过做类似

的事情
<br>
<div>
   <div>
      <h2>User {{ourUSer}}</h2>

</div>

但只有用户出现 有人知道如何最好地做到这一点吗?

而不是像这样设置值:

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

可以在要渲染值的组件中声明一个变量,设置为this.ourUser值:

yourVariable = this.ourUser;

然后用它来显示模板中的值:

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