Selectors help you get specific pieces of data from your app's state. They can also create new data by combining or changing existing state values.
0
0
Selectors for derived state in Angular
Introduction
You want to show a list filtered by user input without changing the original list.
You need to calculate a total price from items in a shopping cart.
You want to combine user info and settings into one object for display.
You want to avoid repeating code that picks parts of the state in many places.
Syntax
Angular
import { createSelector } from '@ngrx/store'; const selectFeature = (state) => state.feature; const selectDerived = createSelector( selectFeature, (feature) => { // return derived data here } );
createSelector takes one or more selectors as input and a function that returns new data.
The function runs only when input data changes, improving performance.
Examples
This selector returns the number of items in the list.
Angular
const selectItems = (state) => state.items; const selectItemCount = createSelector( selectItems, (items) => items.length );
This combines user and settings data into one object.
Angular
const selectUser = (state) => state.user; const selectSettings = (state) => state.settings; const selectUserProfile = createSelector( selectUser, selectSettings, (user, settings) => ({ name: user.name, theme: settings.theme }) );
Sample Program
This Angular component shows a shopping cart list and the total price. The total price is calculated using a selector that sums item prices times quantities.
Angular
import { Component } from '@angular/core'; import { createSelector } from '@ngrx/store'; interface AppState { cart: { items: { name: string; price: number; quantity: number }[] }; } const state: AppState = { cart: { items: [ { name: 'Apple', price: 1, quantity: 3 }, { name: 'Banana', price: 2, quantity: 2 } ] } }; const selectCartItems = (state: AppState) => state.cart.items; const selectTotalPrice = createSelector( selectCartItems, (items) => items.reduce((total, item) => total + item.price * item.quantity, 0) ); @Component({ selector: 'app-cart', standalone: true, template: ` <h2>Shopping Cart</h2> <ul> <li *ngFor="let item of items">{{item.name}} x{{item.quantity}} - ${{item.price}}</li> </ul> <p><strong>Total: ${{total}}</strong></p> ` }) export class CartComponent { items = state.cart.items; total = selectTotalPrice(state); }
OutputSuccess
Important Notes
Selectors help keep your UI code clean by moving data logic out of components.
Using selectors improves performance because they only recalculate when needed.
Summary
Selectors get and create data from your app state.
They help avoid repeating code and improve performance.
Use createSelector with input selectors and a function to make derived data.