Frank
Frank

Reputation: 442

ngFor does not update when new data is sent to the variable of type array

I am trying to make the page update data through ngFor but it is impossible. I have two components app.component and secondComponent.

In the app.component there is a button that when pressed activates the change() function in the secondComponent. This function updates an array type variable. The problem arises when the array is updated but not the DOM.

app.component.ts

export class AppComponent {
 
  data: string = 'A1';
  constructor(private second: SecondComponent) {}

  send() {
    this.second.change(this.data);
  }
}

app.component.html

<p>APP COMPONENT</p>
<button class="button" (click)="send()">Push</button>

<secondComponent-app></secondComponent-app>

secondComponent.ts

export class SecondComponent {
  box1: any = ['car', 'plane'];

  change(data) {
    if (data == 'A1') {
      this.box1 = ['car1', 'plane1'];
    }

    console.log(this.box1);
  }
}

secondComponent.html

<p>SECOND COMPONENT</p>
<div *ngFor="let item of box1 ">{{item}}</div>

Can anybody help me?. Thanks in advance. See StackBlitz https://angular-ivy-qbeqzo.stackblitz.io/

Upvotes: 1

Views: 1010

Answers (1)

Zircon
Zircon

Reputation: 4707

In your parent component's constructor, Angular is injecting an instance of your SecondComponent (it would seem) that is a different instance than the one in your component's template specified by <secondComponent-app>

Instead of putting it into the constructor, do the following:

  1. Add an angular identifier to your child component tag (denoted by a #), e.g. <secondComponent-app #second>
  2. Use @ViewChild to gain access to the component in the template in your parent's class body like so:
export class AppComponent {
 
  data: string = 'A1';
  @ViewChild('second', { static: true }) second: SecondComponent;

You should then be able to handle the SecondComponent as a field of your parent.

More info: https://angular.io/api/core/ViewChild

Upvotes: 1

Related Questions