Currently, I am utilizing *ngFor to present values from an array:
[
{
id: 1,
name: 'item1'
},
{
id: 2,
name: 'item2'
}
]
In the html:
<div *ngFor="let item of (items$ | async); trackBy: trackById;">
// additional html for displaying data
</div
In the ts file:
items$: Observable<any>;
trackById = trackByProperty('id');
ngOnInit() {
this.items$ = this.store.pipe(select(selectors.itemsSelector));
}
trackByProperty<T = any>(property: keyof T) {
return (index: number, object: T) => object[property];
}
This method is functioning as expected, as ngFor captures the correct and current values in the items$ array
The problem arises when I update the items$
array through ngrx
, it fails to detect the new array and does not refresh the DOM accordingly.
Here is the sequence of events using ngrx
:
A dispatch action is sent to the reducer, containing a new object to add to the array.
this.store.dispatch(new actions.UpdateArray( { id: 3, name: 'item3' } ) );
The reducer processes this action by updating the store state with the modified array (including the new item).
case actions.UPDATE_ARRAY: { const newItem = action.payload; const items = state.items; items.push(newItem); return { ...state, items }; }
The selector updates.
I have verified that the state is updated correctly by logging out the action.payload within the reducer.
Any insights on why the *ngFor
does not reflect the updated array?
Note: I am using
changeDetection: ChangeDetectionStrategy.OnPush
as the change detection strategy in my component
Update
I discovered that the DOM does update when clicking on the component. Ideally, I would like it to update without requiring user interaction.