I have a problem with ngFor while using Angular OnPush ChangeDetection.
This is my code:
app.state.ts
export class Node {
title: string;
}
export class Tree {
nodes: Array<Node>
}
home.component.ts
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeComponent implements OnInit {
tree$: Observable<Tree>;
ngOnInit() {
this.tree$ = this.store.select(state => state.tree);
}
}
home.component.html
Number of nodes: {{ (tree$ | async).nodes.length }}
<div *ngFor="let node of (tree$ | async).nodes" class="node-list">
{{ node.title }}
</div>
By default, the nodes array is empty. When I dispatch an action to add a new node into the nodes array. The number of nodes in the template changes, but the node list is still empty.
I don't understand why. Do you have any idea? Thanks!
UPDATE By adding *ngIf in a container that contains node list, it is working.
<div *ngIf="tree$">
<div *ngFor="let node of (tree$ | async).nodes" class="node-list">
{{ node.title }}
</div>
</div>
But I still do not understand why. Could you explain this behavior, please?