NgRx State Selectors

NgRx State Selectors

As our application grows, the data structure that represents the application states could get more complex. State data structure in ngRx is tree-like and in the early development, the structure may only have few properties. As the application grows, the structure could have deep nested objects.

When states have deep nested objects, we will have to write more code to select the slice of state. Something like:

// Complex data structure
let state = {
    products: {
        pizza: {
            name: "Pepperoni",
            amount: 4
        },
        topping: {
            name: "mushroom",
            amount: 3
        }
    }
};

// Selecting pizza state
let pizza = state.products.pizza;

Selecting pizza state requires dot notation and it’s also prone to error where products is undefined, that line of code will blow up.

Another issue with this is that we will have to write the same line of code to get pizza state every where we need the state.

This is where state selectors in ngRx comes in. It allows us to define selectors for our states and use it everywhere in our application.

There are mainly 2 state selectors, createFeatureSelector and createSelector. The first one mainly deals with state at the root level while the second one can be used to select a specific object in the state (for example, pizza or topping).

Reference

https://toddmotto.com/ngrx-store-understanding-state-selectors

Advertisements

NgRx Store Explained

NgRx Store

ngRx Store is a library for Angular 2+, its function is almost like event bus where the store is a central storage for all events and whenever an event is added, the store emits an action. Whoever subscribe to the store‘s action will then get notified. Very similar to pub-sub pattern.

The purpose of ngRx Store is to simplify the state management, that sometime can be simple at first but, as the application grows, becomes unimaginably complicated.

Some example usage of ngRx Store that I can think right now are:

  • Forward execution. When an Angular application sends an API call to update, let’s say, employee data, it doesn’t need to call API anymore to query what the current employee data is. However, things get complicated when there’s a certain logic needs to be applied when updating employee data. For example, when the hire date is set to the future, the employee status will also need to be changed. ngRx Store can be used to manage the employee state so that it remains consistent at every part of the application.
  • Reduce extraneous props. Extraneous prop is when we have a deep component tree and have to pass object around to the leaf component. ngRx Store eliminates the need of passing the object around and just have the leaf component subscribe to the `store` to receive the action. A concrete example of this is notification counter. The counter is normally in its own component and every other event can increase the count. By using ngRx Store, we can avoid other components passing the count to the counter component.
  • Sort of the similar to extraneous props, we can have 2, or more, components that use the same data but display it differently. With ngRx Store, we can manage the state of the data in one place and all other components that use the data just subscribe to it.
  • Step-by-step, wizard-y workflow. Think of this like your tax filing software where it asks you questions and, depend on your answer, take you to different workflow. In Angular, each step the users take can use a separate component and ngRx Store can be used to maintain the state of the whole workflow process.

The problem that ngRx Store trying to solve is really similar to challenges that a large scale enterprise application faces, it just does it in a smaller scale, UI front-end in this case.

There’s definitely a lot more to this concept than what I cover here, but hopefully this gives you the gist of how it works at the high level. There are lots of resources online that cover this very topic.

Karma: Only Run 1 Test

Useful hack to only run 1 test in Karma.

Instead of ‘it’, change test declaration to ‘fit’.
Example:

    fit('should create', () => {
        expect(component).toBeTruthy();
    });

This will force Karma to only run ‘should create’ test.

How to Get ElementRef DOM

ElementRef exposes nativeElement in which you could access its HTML DOM.

ng-now.component.ts

import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-ng-now',
  template: `
    <div>
      This is the View

      <ng-content></ng-content>
    </div>
  `
})

export class NgNowComponent implements AfterContentInit {
  @ContentChild('theElement') theElement: ElementRef;

  constructor() { }

  ngAfterContentInit() {
    console.log('======== Get ElementRef DOM');
    console.log(this.theElement.nativeElement.innerHTML);
  }

}

app.component.html

<app-ng-now>
    <div #theElement>
        <span>the element goes here</span>
    </div>
</app-ng-now>

How to Get EmbeddedViewRef DOM

EmbeddedViewRef allows you to get its HTML DOM from its rootNodes properties.

ng-now.component.ts

import { Component ViewChild, ContentChild, TemplateRef, ViewContainerRef, AfterContentInit, EmbeddedViewRef } from '@angular/core';

@Component({
  selector: 'app-ng-now',
  template: `
    <div #theView>
      This is the View
    </div>
`
})

export class NgNowComponent implements AfterContentInit {
  @ContentChild(TemplateRef) theTemplate: TemplateRef;
  @ViewChild('theView', { read: ViewContainerRef }) theViewContainerRef: ViewContainerRef;
  theEmbView: EmbeddedViewRef;

  constructor() { }

  ngAfterContentInit() {
    this.theEmbView = this.theViewContainerRef.createEmbeddedView(this.theTemplate);

    console.log('============ Get EmbeddedViewRef DOM')
    console.log(this.theEmbView.rootNodes[0]);
  }
}

app.component.html

<app-ng-now>
    <ng-template>
        <span>the template goes here</span>
    </ng-template>
</app-ng-now>