Increasing binding specificity

Let’s say we want to trigger an action when the user hits enter on their keyboard. We could do something like this, capturing the keydown event and then decide what to do based on the entered key:

While the above works, it’s pretty verbose. Instead, we can make our binding more specific by doing the following:

Now, that’s a lot more specific and less verbose. The same goes for class bindings. Here’s a lengthy example:

Since all we want to do is toggle the green class on or off based on a boolean expression, the following syntax is shorter and better:

You can see these examples in action on Stackblitz.

State Management: Selector

We know how to create a State and dispatch actions to update its value. Now let’s see how to receive updates when the State gets updated.

Most state management libraries provide what is known as Selectors. A Selector query function runs against our State and returns an Observable. For instance, with NgXs, a Selector can be created with the @Select decorator as follows:

The above code creates an Observable that returns any value update in state.currencyInfo. If you don’t like decorators, you can also use the select function from the Store service:

Both options return a similar Observable. If a Selector of a slice of your State is used repeatedly, you can make it a memoized selector by using the @Selector decorator in your State class. This example creates a new selector that returns just the currency property of our State:

Such a Selector can be used with @Select decorator in your components/services as follows:

You can see that code in action on Stackblitz.