Martin
Martin

Reputation: 55

Can't read variable in component's html file in Angular

I am trying to display an array's data (populated in 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>

.. without any luck!

The console.log() shows me that the array is populated correctly: (3) ["3", "5", "6"].

loadMatches() is called from another component home.component..

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

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

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

Why isn't matchesList's data accessible in chat.component.html ?

Thank you!

Upvotes: 0

Views: 779

Answers (1)

user2216584
user2216584

Reputation: 5602

This is happening because the instance which you use to call this.chatComp.loadMatches() is not the same as the one which was used for the rendering following template -

chat.component.html

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

You have used providers: [ChatComponent] which will give you a different instance as compared to the one used for rendering.

We will be able to help you further if you can share your html/.ts files for the following components and also the code [html] which places the component in your UI -

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?]

Upvotes: 2

Related Questions