DEV Community

Cover image for Use Ngrx Selectors with Parameters
James Prince
James Prince

Posted on

Use Ngrx Selectors with Parameters

Selecting data from an Ngrx store has always been achieved by using selectors. As Ngrx has developed over the last couple of years, selectors have become easier and easier to use.

interface Customer { id: number; name: string; }
interface AppState { customers: Customer[] }

export const selectCustomers = (state: AppState) => state.customers;
Enter fullscreen mode Exit fullscreen mode

The above selectCustomers selector conveniently returns Customers from the store.


How can we select a single customer entity from the store by its id?

To do this is nice and simple in Ngrx 12+; we can use a factory selector.

import { createSelector } from '@ngrx/store';

interface Customer { id: number; name: string; }
interface AppState { customers: Customer[] }

export const selectCustomers = (state: AppState) => state.customers;

// selector with param
export const selectCustomerById = (customerId: number) =>
  createSelector(
    selectCustomers, 
    (customers: Customers[]) => 
      customers.find(c => c.id === customerId) 
  )
Enter fullscreen mode Exit fullscreen mode

We can then get a customer with the id of 123 from the store; by passing a value for the customerId into our selector:

this.store.select(selectCustomerById(123));
Enter fullscreen mode Exit fullscreen mode

Hope this helps you all out as the older method of using props is now deprecated in Ngrx 12+. (https://github.com/ngrx/platform/issues/2980)

I also have a YouTube channel called Coffee Music & Coding which you may find useful for Angular and Ngrx tutorials.

Top comments (2)

Collapse
 
spock123 profile image
Lars Rye Jeppesen

thanks

Collapse
 
kloudja profile image
kloudja

Thanks! Simple and easy