Reputation: 442
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
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:
#
), e.g. <secondComponent-app #second>
@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