首页 > 解决方案 > 无法在Angular中读取组件的html文件中的变量

问题描述

我正在尝试显示数组的数据(填充在 中chat.component)..

public matchesList = [];

loadMatches() {
...
    if (result.success) {
      this.matchesList = result.matches_list.split(',');
      console.log(this.matchesList);
    }
}

..在chat.component.html..

<div class="matchesList" *ngFor="let match of matchesList">
    <p>{{match}}</p>
</div>

..没有任何运气!

console.log()我展示了该数组已正确填充:(3) ["3", "5", "6"].

loadMatches()从另一个组件调用home.component..

import { ChatComponent } from '../chat/chat.component';

@Component({
  providers: [ChatComponent],
  ...
})

loadChatViewData() {
    this.chatComp.loadMatches();
}
<a class="nav-link" (click)="loadChatViewData()"></a>

为什么matchesList的数据不能在 中访问chat.component.html

谢谢!

标签: angular

解决方案


发生这种情况是因为您用来调用的实例this.chatComp.loadMatches()与用于渲染以下模板的实例不同 -

chat.component.html

<div class="matchesList" *ngFor="let match of matchesList">
    <p>{{match}}</p>
</div>

providers: [ChatComponent]与用于渲染的实例相比,您使用的实例将为您提供不同的实例。

如果您可以共享以下组件的 html/.ts 文件以及将组件放置在您的 UI 中的代码 [html],我们将能够为您提供进一步的帮助 -

1. Chat Component.ts/.html
2. Home component.ts/.html
3. The parent [if any] which holds those two components [If not then let us know how those are rendered [i.e. Parent/Child?]

推荐阅读