Ilya Loskutov
Ilya Loskutov

Reputation: 2201

How to add entity to array like model and get back index from store?

My state model is

//for reducer
export class State { 
    items: Item [];
}

export class Item {
    id: string;
    name: string;
    error: any;
    pending: boolean;
}

The idea of array model is a component can have multiple places where an item state is displaying at the moment of time (so the first is pending, the second has fetched name from server yet, etc.).

For the adding of new item I use action with the type like "ADD_NEW_ITEM". Reducer can push new item instance to the items array, it's not a problem. However my component should be aware about what index of items is binded with some template place to do something like:

<p *ngIf="(state$ | async).items[0].name">Name is {{(state$ | async).items[0].name}}</p>

But there is no any possibility for the component to get new index from the store after ADD_NEW_ITEM dispatches immediately

So can I solve it? The only my thought is the component have to pass some unique id self with ADD_NEW_ITEM action. But I don't find this as elegant way.

Update: the reason I can't use ngFor here is that state (array) is shared, i.e. is not only for the current active component. Therefore the cmp have to be aware aboute "its" entities, is added by the one

Upvotes: 0

Views: 621

Answers (1)

tlt
tlt

Reputation: 15271

You have 2 options here:

1) If you really need to know last item added explicitly, then you need to put it in the store and bind your control to it. Your ADD_NEW_ITEM action would update both: collection of items and lastItemAdded. your reducer would then, in turn, expose reducer.getLastItemAdded to get it from store.

2) In your component, you can implement OnChanges and inspect when your @Input() items change and compare to old collection (you have currentValue/lastValue in changes object) and deduct that way what is the new item.

ref: https://angular.io/guide/lifecycle-hooks#onchanges

Upvotes: 1

Related Questions