Search code examples
angularjsngrxngrx-store-4.0

ngrx parameter to select function


Is there a way to pass parameters to ngrx select functions?

Following is my use case:

I am maintaining list of comments in store.

I wrote one component to represent one comment. So, one CommentComponent knows the id of the component object

Each comment will have properties like likedBy, reportedBy, ...etc In UI, I am showing all the components using *ngFor

Now I want my CommentComponent to subscribe only to one comment object by using id of the component.

Right now I am subscribing to all the comments in a top level component, and passing each comment to the CommentCompoent as an input.

Current approach is not clean because angular change detection strategy (even if I use onPush) has to render DOM for all the comments even though only one comment changes.

Appreciate any suggestions where I can pass comment id to a selector function so that each CommentComponent can subscribe to only one comment.

Thanks in advance, Sudhakar


Solution

  • As of NgRx 6.1, you can use a selector with props.

    export const getCount = () =>   
      createSelector(     
        (state, props) => state.counter[props.id],     
        (counter, props) => counter * props.multiply
    );
    

    For more info and different ways, check out my article NgRx: Parameterized selectors