I am stuck with the following: I have a parent component in Angular 5 that displays childcomponents for each element in my cartProducts array. My childcomponents receive a cartProduct object as input. My cartProducts are received from a BehaviorSubject object. Whenever I receive updates, I update my array. I expected that all my childcomponents would react on updates to my array, but this does not happen. What am I doing wrong?
parent.component
constructor(private service:Service) {
this.service.cpBehaviorSubject.subscribe({next: (v) => {
console.log('Change triggerend in parent.');
this.cartProducts = v;
}});
}
parent.html
<ng-template ngFor let-cp [ngForOf]="this.cartProducts">
<app-child [cartProduct]="cp"></app-child>
</ng-template>
child.component
ngOnChanges() {
console.log('Change triggered in child!');
}
4 Answers 4
Change cartProducts to receive BehaviorSubject instead and then use async pipe in the template.
cartProducts$;
constructor(private service:Service) {
this.cartProducts$ = this.service.cpBehaviorSubject();
}
<ng-template ngFor let-cp [ngForOf]="this.cartProducts$ | async">
<app-child [cartProduct]="cp"></app-child>
</ng-template>
Comments
Can you try this in your parent component:
constructor(private service:Service) {
this.service.cpBehaviorSubject.subscribe((v) => {
console.log('Change triggerend in parent.');
this.cartProducts = v;
});
}
Comments
Angular does not do change detection on the contents of your array, just on the array reference.
The simplest way to trigger the change detection is to update the array reference after updating the contents of the array with array.slice().
So, for example,
myArray.push(foo);
myArray = myArray.slice();
Comments
What about <ng-template> ? Accourding to the deffinition, a ng-template will not be rendered on the DOM. Clicking to the link below you will be redirected to TekTutorialsHub where you will understand how ng-template work.
https://www.tektutorialshub.com/angular/ng-template-in-angular/
Due to the fact that it is not rendered, the ngOnChanges life cycle hook is not triggered
cpBehaviorSubjectkeep referring to the same cart product instances on each update, or does it return new instances? I suspect that it returns the same instances, and that this is why Angular does not detect any change