Angular (2+) & NgRx/store: The NgModel In Between Use Case (from Angular 1)

In the recent article, I integrated ngrx/store as a redux implementation to Echoes Player. Until this article, the search was static with one hard coded search query. In this article, I'm sharing my insights on migrating more features from angular 1 and implementing ng-model with ngrx.

From Angular 1 To Angular 2: NgModel Template Syntax

In Echoes Player with angular 1, this template is part of the "search-panel" component. It renders the search box to the top of the player:

* I removed some attributes and html code to make this code simpler for this post.

The migration of the html code above is quite simple (I mentioned it in 3 more steps to prepare your angular 1 to angular 2) in angular 2:

  1. ng-model is converted to ([ngModel])
  2. ng-change is converted to (input)
  3. instead of using ng-submit, I used a simple (click) event on the search button

Notice the ngModel is both bind with a value (using the binding [] brackets) and both syncs back to its variable (as an event with () ) - This the 2-way binding we've been used to from angular 1. This template goes inside the youtube-videos template. Here is the full template:

Updating Youtube Videos Component Class

To support the new search feature, the component's class needs to be updated with:

  1. "searchQuery" property which will hold the search string value
  2. Updating the search function with the new "searchQuery"
  3. "resetPageToken" function which will reset the pageToken property when the search query  changes

Updating Youtube Search Service With a New NgRx Action

The last change goes to the youtube search service - this is where the actual search logics happens and where NgRx/store goes into action.

I added a new function "resetPageToken", which purpose is to reset the pageToken property in the configuration object that is used in the youtube search request.

This function also dispatched a new action, 'RESET', which resets the videos list in the store. It is also being called in the search function if a new search is request by Echoes:

This is the result:

Screen Shot 2016-02-19 at 3.45.55 PM