Search⌘ K
AI Features

Example of Selectors

Explore how to implement Selectors in NgRx to retrieve slices of state data efficiently within Angular applications. This lesson helps you understand the use of createSelector and createFeatureSelector methods for accessing feature state and improving performance by avoiding redundant state retrieval calls. You'll also learn how to subscribe to selector results in components, enhancing your skills in reactive state management using NgRx.

What is the Selector?


The Selector allows us to get information for the State store without having to return the entire store.


Selectors are pure functions in NgRx, similar to Reducers.

NgRx helper functions

NgRx provides two helper functions: createSelector() and createFeatureSelector()

createFeatureSelector() method

The createFeatureSelector() method gets the feature state (the state of a feature module),

createSelector() method

The createSelector() method returns a selection of that State information. As you can see, we can use the first method to get the State of a feature and the second type of Selector to get a slice of data from that first State.

Both of these methods are from the NgRx Selector API. What’s really clever about these two helper functions is that when NgRx sees we’re running a Selector with the same two arguments we used previously to get state data, instead of going off and repeating what NgRx has just done, it just returns the same State as it did before without the round trip to go and get the data. The NgRx Store keeps track of the Selectors that have been used, and if we use one that it knows of, it invokes that Selector again without having to run the same selector code again. This gives us a great performance boost.

Getting State using a Selector

Let’s look at an example of creating a Selector to retrieve data from our ApplesState.

Step 1: Create a Selector

Here, we are creating a selector using createSelector() method that returns a selection of the state information.

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

import { ApplesState } from '../state/apples.state';

const selectApples = (state: ApplesState) => state;

export const selectApplesFromStore = createSelector(
  selectApples,
  (state: ApplesState) => state.applesCount
);

Step 2: Subscribe to Results

To use these Selectors in a component, we import these Selectors into our component and then subscribe to the results using the Async pipe in the app.component.html:

📝 Note: Press the RUN button to compile and serve the application. Once the app compiles, click on the URL given after Your app can be found at, and see what happens!

import { AppPage } from './app.po';
import { browser, logging } from 'protractor';

describe('workspace-project App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getTitleText()).toEqual('Client-Contacts-Manager-Angular app is running!');
  });

  afterEach(async () => {
    // Assert that there are no errors emitted from the browser
    const logs = await browser.manage().logs().get(logging.Type.BROWSER);
    expect(logs).not.toContain(jasmine.objectContaining({
      level: logging.Level.SEVERE,
    } as logging.Entry));
  });
});
Angular application with Selectors

See how the “Total Number of Apples in Store” changes by adding and removing Apples.

In this example, we make use of the Store class from NgRx so that we can use the select() method in order to invoke the Selector. Then, we subscribe to the Observable returned from the select() method. You will notice that we’re not using a Service to get the data as we may have done if we weren’t using NgRx. This is because we are now using the Selectors to get data from the State instead of using a Service to load in data.

This does raise the question of, if we aren’t using Services to load data into our smart components, how do we handle loading data from external sources such as APIs? This is where Effects come into play, which we will look at next.