Back to results for “Templates”
Angular › NgRx State Management

How do you select a specific piece of state from the NgRx store and use it in a component?

Intermediate

Answer

You use a selector function, created with createSelector, to describe exactly which piece of state you want, then inject the Store service and call its select method with that selector, receiving an observable that automatically emits whenever that specific piece of state changes.
export const selectCartItems = createSelector(
  (state: AppState) => state.cart,
  (cart) => cart.items
);

constructor(private store: Store<AppState>) {}
cartItems$ = this.store.select(selectCartItems);
Real-world example A shopping cart badge component displays the current number of items by selecting just that specific piece of state from the store, automatically updating whenever an item is added or removed anywhere else in the app.

Common follow-ups: Why are selectors considered more efficient than manually filtering the entire state object yourself?;How do you combine multiple selectors together to derive a new computed value?