Home > Enterprise >  Angular ngRx how to Refreshing a component for a new state
Angular ngRx how to Refreshing a component for a new state

Time:02-21

I have a doubt about how to update a component, I am making a web app with Angular (lastest version) and I am using ngRx to manage the state.

my web has a Gridview with items where each item is a component (see the image)

Now, I want to update the data inside of ItemComponent, for example the first one item (without add a subcriber in every Item component) but I don't know how to do it.

What is the best way to do this? I want to update any item totally independient between them because if I add a subscribe inside the ItemComponent then I will have to add an conditional to check the component id and exclude it if it's different

I hope I have explained correctly

enter image description here

CodePudding user response:

  1. add a list of items for the grid to your ngrx store
  2. grid view component selects that list of items for display
  3. grid view component passes each item to an item component
  4. when an item is updated from within an item component, you dispatch an action with the updated item as its payload
  5. the reducer handles the action, and updates the relevant item in the items list
  6. the store emits the complete list with the updated item
  7. the grid view component updates to reflect the changes

Grid view component template:

<grid-view-item *ngFor="item of items$ | async" [item]="item"></grid-view-item>

Grid view component class:

items$ = this.store.select(selectItems);

Grid view item component template:

<p>Name: {{ item.name }} </p>
// etc

Grid view item component class:

@Input item: GridViewItem;

// call this depending on your implementation
onEdited(updatedItem: GridViewItem){
  this.store.dispatch(gridViewItemUpdatedAction(updatedItem));
}

Reducer
Replace the updated item, leave the rest as they are:

on(gridViewItemUpdatedAction, (state, { updatedItem }) => ({
  ..state,
  items: items.map(item => item.id === updatedItem .id ? updatedItem : item)
}),
  • Related