【问题标题】:Can't read variable in component's html file in Angular无法在Angular中读取组件的html文件中的变量
【发布时间】:2025-12-17 05:55:02
【问题描述】:

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

public matchesList = [];

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

..in 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 中访问?

谢谢!

【问题讨论】:

  • 这不是你使用组件的方式,你不需要将它添加到组件providers:[...]。用于服务。
  • @marshalllegend 感谢您的回答,我该怎么办?
  • this post 中的答案应该有助于阐明如何在子组件中调用方法。
  • @marshalllegend 非常感谢!它现在工作正常,我需要深入了解更多文档!再次感谢
  • 太棒了,很高兴听到它!

标签: angular


【解决方案1】:

发生这种情况是因为您用来调用 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?]

【讨论】: