<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wes on Medium]]></title>
        <description><![CDATA[Stories by Wes on Medium]]></description>
        <link>https://medium.com/@wesgrimes?source=rss-9af1d23366c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Xs16INTB3SU_JuBLyOj3sA.jpeg</url>
            <title>Stories by Wes on Medium</title>
            <link>https://medium.com/@wesgrimes?source=rss-9af1d23366c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:53:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wesgrimes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Deep Dive into Angular’s NgOnDestroy]]></title>
            <link>https://medium.com/angular-in-depth/https-medium-com-wesgrimes-making-upgrades-to-angular-ngondestroy-90c6bc95166e?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c6bc95166e</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 10:34:51 GMT</pubDate>
            <atom:updated>2020-04-29T21:16:31.693Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Deep Dive into Angular NgOnDestroy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_iR86JGqc-cKgd3t.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*KrSbA_LjhCu8yp4Q.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>This article is a continuation of an Angular Hot Tip tweet that I sent out earlier this week. It became widely popular and generated quite a discussion. The concepts explored in this article reflect that discussion, so you should probably take some time and go check it out here:</p><h3>Wes on Twitter</h3><p>📣🌟Angular Hot Tip Counting on ngOnDestroy to always fire? You may be surprised to learn that it doesn&#39;t fire on page refresh or navigation away from your application. How do we fix that? Decorate with HostListener(&quot;window:beforeunload&quot;) #javascript @angular</p><p>As an extension of the above mentioned tweet, we will discuss limitations with how and when ngOnDestroy is called. We will also discuss ways to overcome those limitations. If you are new to Angular, or new to lifecycle methods in Angular, then I suggest you check out the <a href="https://angular.io/guide/lifecycle-hooks">official docs here</a>.</p><h3>NPM Package Versions</h3><p>For context, this article assumes you are using the following npm package.json versions:</p><pre>@angular/*: 7.2.9</pre><h3>A Brief Primer On NgOnDestroy</h3><p>Before we dig too deep, let’s take a few minutes and review ngOnDestroy.</p><p>NgOnDestroy is a lifecycle method that can be added by implementing OnDestroy on the class and adding a new class method named ngOnDestroy. It’s primary purpose according to the <a href="https://angular.io/guide/lifecycle-hooks#lifecycle-sequence">Angular Docs</a> is to “Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called just before Angular destroys the directive/component.”</p><h3>A Leaky MyValueComponent</h3><p>Let’s imagine that we have a component named MyValueComponent that subscribes to a value from MyService in the ngOnInit method:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { MyService } from &#39;./my.service&#39;;<br><br>@Component({<br>  selector: &#39;app-my-value&#39;,<br>  templateUrl: &#39;./my-value.component.html&#39;,<br>  styleUrls: [ &#39;./my-value.component.css&#39; ]<br>})<br>export class MyValueComponent implements OnInit {<br>  myValue: string;<br><br>  constructor(private myService: MyService) {}<br><br>  ngOnInit() {<br>      this.myService.getValue().subscribe(value =&gt; this.myValue = value);<br>  }<br>}</pre><p>If this component is created and destroyed multiple times in the lifecycle of an Angular application, each time it’s created the ngOnInit would be called creating a brand new subscription. This could quickly get out of hand, with our value being updated exponentially. This is creating what is called a “memory leak”. Memory leaks can wreak havoc on the performance of an application and in addition add unpredictable or unintended behaviors. Let’s read on to learn how to plug this leak.</p><h3>Fixing the Leak on MyValueComponent</h3><p>To fix the memory leak we need to augment the component class with an implementation of OnDestroy and unsubscribe from the subscription. Let’s update our component adding the following:</p><ul><li>Add OnDestroy to the typescript import</li><li>Add OnDestroy to the implements list</li><li>Create a class field named myValueSub: Subscription to track our subscription</li><li>Set this.myValueSub equal to the value of this.myService.getValue().subscription</li><li>Create a new class method named ngOnDestroy</li><li>Call this.myValueSub.unsubscribe() within ngOnDestroy if a subscription has been set.</li></ul><p>The updated component will look something like this:</p><pre>import { Component, OnInit, OnDestroy } from &#39;@angular/core&#39;;<br>import { MyService } from &#39;./my.service&#39;;<br><br>@Component({<br>  selector: &#39;app-my-value&#39;,<br>  templateUrl: &#39;./my-value.component.html&#39;,<br>  styleUrls: [ &#39;./my-value.component.css&#39; ]<br>})<br>export class MyValueComponent implements OnInit, OnDestroy {<br>  myValue: string;<br>  myValueSub: Subscription;<br><br>  constructor(private myService: MyService) {}<br><br>  ngOnInit() {<br>      this.myValueSub = this.myService.getValue().subscribe(value =&gt; this.myValue = value);<br>  }<br><br>  ngOnDestroy() {<br>    if (this.myValueSub) {<br>        this.myValueSub.unsubscribe();<br>    }<br>  }<br>}</pre><h3>Moving Beyond Memory Leaks</h3><p>Great! Now you have some background on ngOnDestroy and how cleaning up memory leaks is the primary use case for this lifecycle method. But what if you want to take it a step further and add additional cleanup logic? How about making server-side cleanup calls? Maybe preventing user navigation away?</p><p>As you read on we will discuss three methods to upgrade your ngOnDestroy for optimum use.</p><h3>Hot Tip #1 — Making NgOnDestroy Async</h3><p>As with other lifecycle methods in Angular, you can modify ngOnDestroy with async. This will allow you to make calls to methods returning a Promise. This can be a powerful way to manage cleanup activities in your application. As you read on we will explore an example of this.</p><h3>Adding logic to call AuthService.logout from ngOnDestroy</h3><p>Let’s pretend that you need to perform a server-side logout when MyValueComponent is destroyed. To do so we would update the method as follows:</p><ul><li>Add AuthService to your imports</li><li>Add AuthService to your constructor</li><li>Add async in front of the method name ngOnDestroy</li><li>Make a call to an AuthService to logout using the await keyword.</li></ul><p>Your updated MyValueComponent will look something like this:</p><pre>import { Component, OnInit, OnDestroy } from &#39;@angular/core&#39;;<br>import { MyService } from &#39;./my.service&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Component({<br>  selector: &#39;app-my-value&#39;,<br>  templateUrl: &#39;./my-value.component.html&#39;,<br>  styleUrls: [ &#39;./my-value.component.css&#39; ]<br>})<br>export class MyValueComponent implements OnInit, OnDestroy {<br>  myValue: string;<br>  myValueSub: Subscription;<br><br>  constructor(private myService: MyService, private authService: AuthService) {}<br><br>  ngOnInit() {<br>      this.myValueSub = this.myService.getValue().subscribe(value =&gt; this.myValue = value);<br>  }<br><br>  async ngOnDestroy() {<br>    if (this.myValueSub) {<br>        this.myValueSub.unsubscribe();<br>    }<br><br>    await this.authService.logout();<br>  }<br>}</pre><p>Tada! Now when the component is destroyed an async call will be made to log the user out and destroy their session on the server.</p><h3>Hot Tip #2 — Ensure Execution During Browser Events</h3><p>Many developers are surprised to learn that ngOnDestroy is only fired when the class which it has been implemented on is destroyed within the context of a running browser session.</p><p>In other words, ngOnDestroy is <em>not</em> reliably called in the following scenarios:</p><ul><li>Page Refresh</li><li>Tab Close</li><li>Browser Close</li><li>Navigation Away From Page</li></ul><p>This could be a deal-breaker when thinking about the prior example of logging the user out on destroy. Why? Well, most users would simply close the browser session or navigate to another site. So how do we make sure to capture or hook into that activity if ngOnDestroy doesn’t work in those scenarios?</p><h3>Decorating ngOnDestroy with HostListener</h3><blockquote><em>TypeScript decorators are used throughout Angular applications. More information can be found here in the </em><a href="https://www.typescriptlang.org/docs/handbook/decorators.html"><em>official TypeScript docs</em></a><em>.</em></blockquote><p>To ensure that our ngOnDestroy is executed in the above mentioned browser events, we can add one simple line of code to the top of ngOnDestroy. Let’s continue with our previous example of MyValueComponent and decorate ngOnDestroy:</p><ul><li>Add HostListener to the imports</li><li>Place @HostListener(&#39;window:beforeunload&#39;) on top of ngOnDestroy</li></ul><p>Our updated MyValueComponent will look something like this:</p><pre>import { Component, OnInit, OnDestroy, HostListener } from &#39;@angular/core&#39;;<br>import { MyService } from &#39;./my.service&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Component({<br>  selector: &#39;app-my-value&#39;,<br>  templateUrl: &#39;./my-value.component.html&#39;,<br>  styleUrls: [ &#39;./my-value.component.css&#39; ]<br>})<br>export class MyValueComponent implements OnInit, OnDestroy {<br>  myValue: string;<br>  myValueSub: Subscription;<br><br>  constructor(private myService: MyService, private authService: AuthService) {}<br><br>  ngOnInit() {<br>      this.myValueSub = this.myService.getValue().subscribe(value =&gt; this.myValue = value);<br>  }<br><br>  @HostListener(&#39;window:beforeunload&#39;)<br>  async ngOnDestroy() {<br>    if (this.myValueSub) {<br>        this.myValueSub.unsubscribe();<br>    }<br><br>    await this.authService.logout();<br>  }<br>}</pre><p>Now our ngOnDestroy method is called both when the component is destroyed by Angular AND when the browser event window:beforeunload is fired. This is a powerful combination!</p><h3>More about HostListener</h3><p>@HostListener() is an Angular decorator that can be placed on top of any class method. This decorator takes two arguments: eventName and optionally args. In the above example, we are passing window:beforeunload as the DOM event. This means that Angular will automatically call our method when the DOM event window:beforeunload is fired. For more information on @HostListener check out the <a href="https://angular.io/api/core/HostListener">official docs</a>.</p><p>If you want to use this to prevent navigation away from a page or component then:</p><ul><li>Add $event to the @HostListener arguments</li><li>Call event.preventDefault()</li><li>Set event.returnValue to a string value of the message you would like the browser to display</li></ul><p>An example would look something like this:</p><pre>@HostListener(&#39;window:beforeunload&#39;, [&#39;$event&#39;])<br>async ngOnDestroy($event) {<br>  if (this.myValueSub) {<br>    this.myValueSub.unsubscribe();<br>  }<br><br>  await this.authService.logout();<br><br>  $event.preventDefault();<br>  $event.returnValue = &#39;A message.&#39;;<br>}</pre><blockquote><em>PLEASE NOTE: This is not officially supported by Angular! </em><em>OnDestroy and </em><em>ngOnDestroy suggest that there is no input argument on </em><em>ngOnDestroy allowed. While unsupported, it does in fact still function as normal.</em></blockquote><h3>More about window:beforeunload</h3><p>window:beforeunload is an event fired right before the window is unloaded. More details can be found in the documentation here: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event.">https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event.</a></p><p>A couple points to be aware of:</p><ul><li>This event is currently supported in all major browsers EXCEPT iOS Safari.</li><li>If you need this functionality in iOS Safari then consider reviewing this <a href="https://stackoverflow.com/questions/14645011/window-onbeforeunload-and-window-onunload-is-not-working-in-firefox-safari-o/14647730#14647730">Stack Overflow thread</a>.</li><li>If you are using this event in an attempt to block navigation away you must set the event.returnValue to a string of the message you would like to display. More details in this <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#Examples">example</a>.</li></ul><h3>Conclusion</h3><p>I realize that some of the tips recommended in this article are not mainstream and may generate some concern. Please remember as always to try these out and see if they fit for what you are doing in your application. If they work great! If not, then it’s ok to move on.</p><p>If you have any comments or questions feel free to contact me on <a href="https://twitter.com/wesgrimes">Twitter</a></p><h3>Additional Resources</h3><p>I would highly recommend enrolling in the Ultimate Angular courses. It is well worth the money and I have used it as a training tool for new and experienced Angular developers. Follow the link below to signup.</p><p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><p><em>Originally published at </em><a href="https://wesleygrimes.com/angular/2019/03/29/making-upgrades-to-angular-ngondestroy.html"><em>wesleygrimes.com</em></a><em> on March 29, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c6bc95166e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/https-medium-com-wesgrimes-making-upgrades-to-angular-ngondestroy-90c6bc95166e">A Deep Dive into Angular’s NgOnDestroy</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing File Uploads With NgRx]]></title>
            <link>https://medium.com/angular-in-depth/managing-file-uploads-with-ngrx-9fe07b084c1b?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fe07b084c1b</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 13:00:44 GMT</pubDate>
            <atom:updated>2020-04-29T21:17:10.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XpWwTDM52OJBxx73.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*X71fdDEfVxley-k2.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>In this article we will build a fully-functional file upload control, that is powered by <strong>Angular</strong> and is backed by an <strong>NgRx</strong> feature store. The control will provide the user with the following features:</p><ul><li>The ability to upload files using the &lt;input #file type=&quot;file&quot; /&gt; HTML element.</li><li>The ability to see an accurate upload progress via the reportProgress HttpClient option.</li><li>The ability to cancel in-process uploads</li></ul><p>As an added bonus, we will briefly dive into building the <em>server-side</em> ASP.NET Core WebAPI Controller that will handle the file uploads.</p><h3>Before We Get Started</h3><p>In this article, I will show you how to manage file uploads using NgRx. If you are new to NgRx, then I highly recommend that you first read my article, <a href="https://wesleygrimes.com/angular/2018/05/30/ngrx-best-practices-for-enterprise-angular-applications.html">NgRx — Best Practices for Enterprise Angular Applications</a>. We will be using the techniques described in that article to build out the NgRx components for file uploads.</p><p>If you are new to Angular, then I recommend that you check out one of the following resources:</p><ul><li><a href="https://bit.ly/2WubqhW">Ultimate Courses</a></li><li><a href="https://angular.io/guide/router">Official Angular Docs</a></li><li><a href="https://ngrx.io/docs">NgRx Docs</a></li></ul><h3>NPM Package Versions</h3><p>For context, this article assumes you are using the following npm package.json versions:</p><ul><li>@angular/*: 7.2.9</li><li>@ngrx/*: 7.3.0</li></ul><h3>Prerequisites</h3><p>Before diving into building the file upload control, make sure that you have the following in place:</p><ol><li>An Angular 7+ application generated</li><li>NgRx dependencies installed</li><li>NgRx Store wired up in your application. <a href="https://wesleygrimes.com/angular/2018/05/30/ngrx-best-practices-for-enterprise-angular-applications.html">e.g. Follow this guide</a></li></ol><h3>Create the Upload File Service</h3><p>Let’s create a brand new service in Angular. This service will be responsible for handling the file upload from the client to the server backend. We will use the amazing <a href="https://angular.io/guide/http">HttpClient</a> provided with Angular.</p><h3>Generate the service</h3><p>$ ng g service file-upload</p><h3>Inject the HttpClient</h3><p>Because we are using the HttpClient to make requests to the backend, we need to inject it into our service. Update the constructor line of code so that it looks as follows:</p><p>constructor(private httpClient: HttpClient) {}</p><h3>Add a private field for API_BASE_URL</h3><blockquote><em>I typically store </em><em>API base URLs in the </em><em>src/environments area. If you&#39;re interested in learning more about </em><em>environmentsin </em><em>Angular then check out this great article: </em><a href="https://blog.angularindepth.com/becoming-an-angular-environmentalist-45a48f7c20d8"><em>Becoming an Angular Environmentalist</em></a></blockquote><p>Let’s create a new private field named API_BASE_URL so that we can use this in our calls to the backend API.</p><p>One way to accomplish this would be to do the following:</p><pre>import { environment } from &#39;src/environments/environment&#39;; <br>... <br>private API_BASE_URL = environment.apiBaseUrl;</pre><h3>Add a uploadFile public method</h3><p>Let’s create a new public method named uploadFile to the service. The method will take in a parameter file: File and return an Observable&lt;HttpEvent&lt;{}&gt;&gt;.</p><blockquote><em>Typically a </em><em>get or </em><em>post </em><em>Observable&lt;T&gt; is returned from a service like this. However, in this situation we are going to actually return the raw </em><em>request which is an </em><em>Observable&lt;HttpEvent&lt;{}&gt;&gt;.</em></blockquote><blockquote><em>By returning a raw </em><em>request we have more control over the process, to pass options like </em><em>reportProgress and allow cancellation of a </em><em>request.</em></blockquote><pre>public uploadFile(file: File): Observable&lt;HttpEvent&lt;{}&gt;&gt; {<br>  const formData = new FormData();<br>  formData.append(&#39;files&#39;, file, file.name);<br><br>  const options = {<br>    reportProgress: true<br>  };<br><br>  const req = new HttpRequest(<br>    &#39;POST&#39;,<br>    `${this.API_BASE_URL}/api/file`,<br>    formData,<br>    options<br>  );<br>  return this.httpClient.request(req);<br>}</pre><h3>Completed File Upload Service</h3><p>The completed file-upload.service.ts will look as follows:</p><pre>public uploadFile(file: File): Observable&lt;HttpEvent&lt;{}&gt;&gt; {<br>  const formData = new FormData();<br>  formData.append(&#39;files&#39;, file, file.name);<br><br>  const options = {<br>    reportProgress: true<br>  };<br><br>  const req = new HttpRequest(<br>    &#39;POST&#39;,<br>    `${this.API_BASE_URL}/api/file`,<br>    formData,<br>    options<br>  );<br>  return this.httpClient.request(req);<br>}</pre><h3>Create the Upload File Feature Store</h3><p>To keep your <strong>NgRx</strong> store organized, I recommend creating a separate Upload File Feature Store. Let’s bundle it all together in a module named upload-file-store.module.ts and keep it under a sub-directory named upload-file-store.</p><h3>Create Feature Store Module</h3><p>Create a feature store module using the following command:</p><p>$ ng g module upload-file-store --flat false</p><h3>Create State Interface</h3><p>Create a new file underneath the upload-file-store folder, named state.ts. The contents of the file will be as follows:</p><blockquote><em>We are using a relatively new technique in that we will set up an </em><em>enum to track the status. This </em><em>enum will reflect the current state of the upload process. For more information on this method, check out </em><a href="https://blog.angularindepth.com/ngrx-how-and-where-to-handle-loading-and-error-states-of-ajax-calls-6613a14f902d"><em>Alex Okrushko&#39;s article</em></a><em>.</em></blockquote><pre>export enum UploadStatus {<br>  Ready = &#39;Ready&#39;,<br>  Requested = &#39;Requested&#39;,<br>  Started = &#39;Started&#39;,<br>  Failed = &#39;Failed&#39;,<br>  Completed = &#39;Completed&#39;<br>}<br><br>export interface State {<br>  status: UploadStatus;<br>  error: string | null;<br>  progress: number | null;<br>}<br><br>export const initialState: State = {<br>  status: UploadStatus.Ready,<br>  error: null,<br>  progress: null<br>};</pre><h3>Create Feature Actions</h3><blockquote><em>If you would like to learn more about </em><strong><em>NgRx Actions</em></strong><em>, then check out the </em><a href="https://ngrx.io/guide/store/actions"><em>official docs</em></a><em>.</em></blockquote><p>Create a new file underneath the upload-file-store folder, named actions.ts. This file will hold the actions we want to make available on this store.</p><p>We will create the following actions on our feature store:</p><ul><li>UPLOAD_REQUEST - This action is dispatched from the file upload form, it&#39;s payload will contain the actual File being uploaded.</li><li>UPLOAD_CANCEL - This action is dispatched from the file upload form when the cancel button is clicked. This will be used to cancel uploads in progress.</li><li>UPLOAD_RESET - This action is dispatched from the file upload form when the reset button is clicked. This will be used to reset the state of the store to defaults.</li><li>UPLOAD_STARTED - This action is dispatched from the file upload effect, HttpClient when the API reports the HttpEventType.Sent event.</li><li>UPLOAD_PROGRESS - This action is dispatched from the file upload effect, HttpClient when the API reports the HttpEventType.UploadProgress event. The payload will contain the progress percentage as a whole number.</li><li>UPLOAD_FAILURE - This action is dispatched from the file upload effect when the API returns an error, or there is an HttpEventType.ResponseHeader or HttpEventType.Response with an event.status !== 200, or when an unknown HttpEventType is returned. The payload will contain the specific error message returned from the API and place it into an error field on the store.</li><li>UPLOAD_COMPLETED - This action is dispatched from the file upload effect when the API reports a HttpEventType.ResponseHeader or HttpEventType.Response event event.status === 200. There is no payload as the API just returns a 200 OK repsonse.</li></ul><p>The final actions.ts file will look as follows:</p><pre>import { Action } from &#39;@ngrx/store&#39;;<br><br>export enum ActionTypes {<br>  UPLOAD_REQUEST = &#39;[File Upload Form] Request&#39;,<br>  UPLOAD_CANCEL = &#39;[File Upload Form] Cancel&#39;,<br>  UPLOAD_RESET = &#39;[File Upload Form] Reset&#39;,<br>  UPLOAD_STARTED = &#39;[File Upload API] Started&#39;,<br>  UPLOAD_PROGRESS = &#39;[File Upload API] Progress&#39;,<br>  UPLOAD_FAILURE = &#39;[File Upload API] Failure&#39;,<br>  UPLOAD_COMPLETED = &#39;[File Upload API] Success&#39;<br>}<br><br>export class UploadRequestAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_REQUEST;<br>  constructor(public payload: { file: File }) {}<br>}<br><br>export class UploadCancelAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_CANCEL;<br>}<br><br>export class UploadResetAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_RESET;<br>}<br><br>export class UploadStartedAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_STARTED;<br>}<br><br>export class UploadProgressAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_PROGRESS;<br>  constructor(public payload: { progress: number }) {}<br>}<br><br>export class UploadFailureAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_FAILURE;<br>  constructor(public payload: { error: string }) {}<br>}<br><br>export class UploadCompletedAction implements Action {<br>  readonly type = ActionTypes.UPLOAD_COMPLETED;<br>}<br><br>export type Actions =<br>  | UploadRequestAction<br>  | UploadCancelAction<br>  | UploadResetAction<br>  | UploadStartedAction<br>  | UploadProgressAction<br>  | UploadFailureAction<br>  | UploadCompletedAction;</pre><h3>Create the Feature Reducer</h3><blockquote><em>If you would like to learn more about </em><strong><em>NgRx Reducers</em></strong><em>, then check out the </em><a href="https://ngrx.io/guide/store/reducers"><em>official docs</em></a><em>.</em></blockquote><p>Create a new file underneath the upload-file-store folder, named reducer.ts. This file will hold the reducer we create to manage state transitions to the store.</p><p>We will handle state transitions as follows for the aforementioned actions:</p><ul><li>UPLOAD_REQUEST - Reset the state, with the exception of setting state.status to UploadStatus.Requested.</li><li>UPLOAD_CANCEL - Reset the state tree. Our effect will listen for any UPLOAD_CANCEL event dispatches so a specific state field is not needed for this.</li><li>UPLOAD_RESET - Reset the state tree on this action.</li><li>UPLOAD_FAILURE - Reset the state tree, with the exception of setting state.status to UploadStatus.Failed and state.error to the error that was throw in the catchError from the API in the uploadRequestEffect effect.</li><li>UPLOAD_STARTED - Set state.progress to 0 and state.status to UploadStatus.Started.</li><li>UPLOAD_PROGRESS - Set state.progress to the current action.payload.progress provided from the action.</li><li>UPLOAD_COMPLETED - Reset the state tree, with the exception of setting state.status to UploadStatus.Completed so that the UI can display a success message.</li></ul><pre>import { Actions, ActionTypes } from &#39;./actions&#39;;<br>import { initialState, State, UploadStatus } from &#39;./state&#39;;<br><br>export function featureReducer(state = initialState, action: Actions): State {<br>  switch (action.type) {<br>    case ActionTypes.UPLOAD_REQUEST: {<br>      return {<br>        ...state,<br>        status: UploadStatus.Requested,<br>        progress: null,<br>        error: null<br>      };<br>    }<br>    case ActionTypes.UPLOAD_CANCEL: {<br>      return {<br>        ...state,<br>        status: UploadStatus.Ready,<br>        progress: null,<br>        error: null<br>      };<br>    }<br>    case ActionTypes.UPLOAD_RESET: {<br>      return {<br>        ...state,<br>        status: UploadStatus.Ready,<br>        progress: null,<br>        error: null<br>      };<br>    }<br>    case ActionTypes.UPLOAD_FAILURE: {<br>      return {<br>        ...state,<br>        status: UploadStatus.Failed,<br>        error: action.payload.error,<br>        progress: null<br>      };<br>    }<br>    case ActionTypes.UPLOAD_STARTED: {<br>      return {<br>        ...state,<br>        status: UploadStatus.Started,<br>        progress: 0<br>      };<br>    }<br>    case ActionTypes.UPLOAD_PROGRESS: {<br>      return {<br>        ...state,<br>        progress: action.payload.progress<br>      };<br>    }<br>    case ActionTypes.UPLOAD_COMPLETED: {<br>      return {<br>        ...state,<br>        status: UploadStatus.Completed,<br>        progress: 100,<br>        error: null<br>      };<br>    }<br>    default: {<br>      return state;<br>    }<br>  }<br>}</pre><h3>Create the Feature Effects</h3><blockquote><em>If you would like to learn more about </em><strong><em>NgRx Effects</em></strong><em>, then check out the </em><a href="https://ngrx.io/guide/effects"><em>official docs</em></a><em>.</em></blockquote><p>Create a new file underneath the upload-file-store folder, named effects.ts. This file will hold the effects that we create to handle any side-effect calls to the backend API service. This effect is where most of the magic happens in the application.</p><h4>Inject Dependencies</h4><p>Let’s add the necessary dependencies to our constructor as follows:</p><pre>constructor(<br>  private fileUploadService: FileUploadService,<br>  private actions$: Actions&lt;fromFileUploadActions.Actions&gt;<br>) {}</pre><h4>Add a new Upload Request Effect</h4><blockquote><em>Effects make heavy-use of </em><em>RxJS concepts and topics. If you are new to </em><em>RxJS then I suggest you check out the </em><a href="https://rxjs.dev/"><em>official docs</em></a></blockquote><p>Let’s create a new effect in the file named uploadRequestEffect$.</p><p>A couple comments about what this effect is going to do:</p><ul><li>Listen for the UPLOAD_REQUEST action and then make calls to the fileUploadService.uploadFile service method to initiate the upload process.</li><li>Use the <a href="https://rxjs.dev/api/operators/concatMap">concatMap</a> RxJS operator here so that multiple file upload requests are queued up and processed in the order they were dispatched.</li><li>Use the <a href="https://rxjs.dev/api/operators/takeUntil">takeUntil</a> RxJS operator listening for an UPLOAD_CANCEL action to be dispatched. This allows us to <strong>short-circuit </strong>any requests that are in-flight.</li><li>Use the <a href="https://rxjs.dev/api/operators/map">map</a> RxJS operator to map specific HttpEvent responses to dispatch specific Actions that we have defined in our Store.</li><li>Use the <a href="https://rxjs.dev/api/operators/catchError">catchError</a> RxJS operator to handle any errors that may be thrown from the HttpClient.</li></ul><p>The effect will look something like this:</p><pre>@Effect()<br>uploadRequestEffect$: Observable&lt;Action&gt; = this.actions$.pipe(<br>  ofType(fromFileUploadActions.ActionTypes.UPLOAD_REQUEST),<br>  concatMap(action =&gt;<br>    this.fileUploadService.uploadFile(action.payload.file).pipe(<br>      takeUntil(<br>        this.actions$.pipe(<br>          ofType(fromFileUploadActions.ActionTypes.UPLOAD_CANCEL)<br>        )<br>      ),<br>      map(event =&gt; this.getActionFromHttpEvent(event)),<br>      catchError(error =&gt; of(this.handleError(error)))<br>    )<br>  )<br>);</pre><h4>Add the getActionFromHttpEvent private method</h4><blockquote><em>For more information on listening to progress events, check out the </em><a href="https://angular.io/guide/http#listening-to-progress-events"><em>official docs guide from here</em></a><em>.</em></blockquote><p>This method will be responsible for mapping a specific HttpEventType to a specific Action that is dispatched.</p><ul><li>HttpEventType.Sent - This event occurs when the upload process has begun. We will dispatch an UPLOAD_STARTED action to denote that the process has begun.</li><li>HttpEventType.UploadProgress - This event occurs when the upload process has made progress. We will dispatch an UPLOAD_PROGRESS action with a payload of progress: Math.round((100 * event.loaded) / event.total) to calculate the actual percentage complete of upload. This is because the HttpClient returns an event.loaded and event.totalproperty in whole number format.</li><li>HttpEventType.Response / HttpEventType.ResponseHeader - These events occur when the upload process has finished. It is important to note that this could be a success or failure so we need to interrogate the event.status to check for 200. We will dispatch the UPLOAD_COMPLETED action if event.status === 200 and UPLOAD_FAILURE if the event.status !== 200 passing the event.statusText as the error payload.</li><li>All Others (default case) — We treat any other events that may be returned as an error because they are unexpected behavior. We will dispatch a UPLOAD_FAILURE action with a payload of the event run through JSON.stringify.</li></ul><pre>private getActionFromHttpEvent(event: HttpEvent&lt;any&gt;) {<br>  switch (event.type) {<br>    case HttpEventType.Sent: {<br>      return new fromFileUploadActions.UploadStartedAction();<br>    }<br>    case HttpEventType.UploadProgress: {<br>      return new fromFileUploadActions.UploadProgressAction({<br>        progress: Math.round((100 * event.loaded) / event.total)<br>      });<br>    }<br>    case HttpEventType.ResponseHeader:<br>    case HttpEventType.Response: {<br>      if (event.status === 200) {<br>        return new fromFileUploadActions.UploadCompletedAction();<br>      } else {<br>        return new fromFileUploadActions.UploadFailureAction({<br>          error: event.statusText<br>        });<br>      }<br>    }<br>    default: {<br>      return new fromFileUploadActions.UploadFailureAction({<br>        error: `Unknown Event: ${JSON.stringify(event)}`<br>      });<br>    }<br>  }<br>}</pre><h4>Add the handleError private method</h4><blockquote><em>For more information on handling </em><em>HttpClient errors, check out the </em><a href="https://angular.io/guide/http#getting-error-details"><em>official docs guide from here</em></a><em>.</em></blockquote><p>This method will be responsible for handling any errors that may be thrown from the HttpClient during requests. I am making use of a neat library from npm named serialize-error to give me a predictable error.message no matter what type of error is thrown.</p><p>Install the library as so:</p><p>$ npm install serialize-error</p><pre>import serializeError from &#39;serialize-error&#39;;<br>...<br>private handleError(error: any) {<br>  const friendlyErrorMessage = serializeError(error).message;<br>  return new fromFileUploadActions.UploadFailureAction({<br>    error: friendlyErrorMessage<br>  });<br>}</pre><h4>Completed Feature Effect</h4><p>The completed effect will look something like this:</p><pre>import { HttpEvent, HttpEventType } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Actions, Effect, ofType } from &#39;@ngrx/effects&#39;;<br>import { Action } from &#39;@ngrx/store&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br>import { catchError, concatMap, map, takeUntil } from &#39;rxjs/operators&#39;;<br>import serializeError from &#39;serialize-error&#39;;<br>import { FileUploadService } from &#39;src/app/_services&#39;;<br>import * as fromFileUploadActions from &#39;./actions&#39;;<br><br>@Injectable()<br>export class UploadFileEffects {<br>  @Effect()<br>  uploadRequestEffect$: Observable&lt;Action&gt; = this.actions$.pipe(<br>    ofType(fromFileUploadActions.ActionTypes.UPLOAD_REQUEST),<br>    concatMap(action =&gt;<br>      this.fileUploadService.uploadFile(action.payload.file).pipe(<br>        takeUntil(<br>          this.actions$.pipe(<br>            ofType(fromFileUploadActions.ActionTypes.UPLOAD_CANCEL)<br>          )<br>        ),<br>        map(event =&gt; this.getActionFromHttpEvent(event)),<br>        catchError(error =&gt; of(this.handleError(error)))<br>      )<br>    )<br>  );<br><br>  constructor(<br>    private fileUploadService: FileUploadService,<br>    private actions$: Actions&lt;fromFileUploadActions.Actions&gt;<br>  ) {}<br><br>  private getActionFromHttpEvent(event: HttpEvent&lt;any&gt;) {<br>    switch (event.type) {<br>      case HttpEventType.Sent: {<br>        return new fromFileUploadActions.UploadStartedAction();<br>      }<br>      case HttpEventType.UploadProgress: {<br>        return new fromFileUploadActions.UploadProgressAction({<br>          progress: Math.round((100 * event.loaded) / event.total)<br>        });<br>      }<br>      case HttpEventType.ResponseHeader:<br>      case HttpEventType.Response: {<br>        if (event.status === 200) {<br>          return new fromFileUploadActions.UploadCompletedAction();<br>        } else {<br>          return new fromFileUploadActions.UploadFailureAction({<br>            error: event.statusText<br>          });<br>        }<br>      }<br>      default: {<br>        return new fromFileUploadActions.UploadFailureAction({<br>          error: `Unknown Event: ${JSON.stringify(event)}`<br>        });<br>      }<br>    }<br>  }<br><br>  private handleError(error: any) {<br>    const friendlyErrorMessage = serializeError(error).message;<br>    return new fromFileUploadActions.UploadFailureAction({<br>      error: friendlyErrorMessage<br>    });<br>  }<br>}</pre><h3>Create the Feature Selectors</h3><blockquote><em>If you would like to learn more about </em><strong><em>NgRx Selectors</em></strong><em>, then check out the </em><a href="https://ngrx.io/guide/store/selectors"><em>official docs</em></a><em>.</em></blockquote><p>Create a new file underneath the upload-file-store folder, named selectors.ts. This file will hold the selectors we will use to pull specific pieces of state out of the store. These are technically not required, but strongly encouraged. Selectors improve application performance with the use of the MemoizedSelector wrapper. Selectors also simplify UI logic.</p><p>We will create a selector for each significant property of the state. This includes the following properties:</p><ul><li>state.status - Since this is an enum we will create a selector for each enum choice.</li><li>state.error</li><li>state.progress</li></ul><p>The completed selectors file will look something like the following:</p><pre>import {<br>  createFeatureSelector,<br>  createSelector,<br>  MemoizedSelector<br>} from &#39;@ngrx/store&#39;;<br>import { State, UploadStatus } from &#39;./state&#39;;<br><br>const getError = (state: State): string =&gt; state.error;<br><br>const getStarted = (state: State): boolean =&gt;<br>  state.status === UploadStatus.Started;<br><br>const getRequested = (state: State): boolean =&gt;<br>  state.status === UploadStatus.Requested;<br><br>const getReady = (state: State): boolean =&gt; state.status === UploadStatus.Ready;<br><br>const getProgress = (state: State): number =&gt; state.progress;<br><br>const getInProgress = (state: State): boolean =&gt;<br>  state.status === UploadStatus.Started &amp;&amp; state.progress &gt;= 0;<br><br>const getFailed = (state: State): boolean =&gt;<br>  state.status === UploadStatus.Failed;<br><br>const getCompleted = (state: State): boolean =&gt;<br>  state.status === UploadStatus.Completed;<br><br>export const selectUploadFileFeatureState: MemoizedSelector&lt;<br>  object,<br>  State<br>&gt; = createFeatureSelector&lt;State&gt;(&#39;uploadFile&#39;);<br><br>export const selectUploadFileError: MemoizedSelector&lt;<br>  object,<br>  string<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getError<br>);<br><br>export const selectUploadFileReady: MemoizedSelector&lt;<br>  object,<br>  boolean<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getReady<br>);<br><br>export const selectUploadFileRequested: MemoizedSelector&lt;<br>  object,<br>  boolean<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getRequested<br>);<br><br>export const selectUploadFileStarted: MemoizedSelector&lt;<br>  object,<br>  boolean<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getStarted<br>);<br><br>export const selectUploadFileProgress: MemoizedSelector&lt;<br>  object,<br>  number<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getProgress<br>);<br><br>export const selectUploadFileInProgress: MemoizedSelector&lt;<br>  object,<br>  boolean<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getInProgress<br>);<br><br>export const selectUploadFileFailed: MemoizedSelector&lt;<br>  object,<br>  boolean<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getFailed<br>);<br><br>export const selectUploadFileCompleted: MemoizedSelector&lt;<br>  object,<br>  boolean<br>&gt; = createSelector(<br>  selectUploadFileFeatureState,<br>  getCompleted<br>);</pre><p>We now need to update the feature module UploadFileStoreModule to wire-up the store.</p><p>The completed UploadFileStoreModule should look similar to this:</p><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { EffectsModule } from &#39;@ngrx/effects&#39;;<br>import { StoreModule } from &#39;@ngrx/store&#39;;<br>import { UploadFileEffects } from &#39;./effects&#39;;<br>import { featureReducer } from &#39;./reducer&#39;;<br><br>@NgModule({<br>  declarations: [],<br>  imports: [<br>    CommonModule,<br>    StoreModule.forFeature(&#39;uploadFile&#39;, featureReducer),<br>    EffectsModule.forFeature([UploadFileEffects])<br>  ]<br>})<br>export class UploadFileStoreModule {}</pre><h4>Import this module where needed</h4><p>Make sure to import this new UploadFileStoreModule where it is needed. In this example, we will import this into the AppModule as we do not have any lazy-loaded features.</p><p>Last, make sure that you update your AppModule to import the StoreModule.forRoot and EffectsModule.forRoot.</p><p>An updated AppModule may look as follows:</p><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { EffectsModule } from &#39;@ngrx/effects&#39;;<br>import { StoreModule } from &#39;@ngrx/store&#39;;<br>import { StoreDevtoolsModule } from &#39;@ngrx/store-devtools&#39;;<br>import { environment } from &#39;src/environments/environment&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { UploadFileStoreModule } from &#39;./upload-file-store/upload-file-store.module&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [<br>    BrowserModule,<br>    HttpClientModule,<br>    StoreModule.forRoot({}),<br>    EffectsModule.forRoot([]),<br>    StoreDevtoolsModule.instrument({<br>      maxAge: 25, // Retains last 25 states<br>      logOnly: environment.production // Restrict extension to log-only mode<br>    }),<br>    UploadFileStoreModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {}</pre><h3>Let’s Review So Far</h3><ul><li>Up to this point, we have created a new FileUploadService that calls our backend API to upload a File object.</li><li>We have also created a new UploadFileStore feature store that provides Actions, a Reducer, Effects, and Selectorsto manage the file upload process.</li><li>Last, the store has been imported into our AppModule for use.</li></ul><p>Now that we have the foundation laid out for us we can turn our attention to the user interface and wire-up a new component to the UploadFileStore that we created to manage our process.</p><p>This will be the fun part!</p><h3>Create the Upload File Component</h3><p>Let’s start by creating a brand-new Component. This component will consist of the following elements:</p><ul><li>An input element for the user to interact with to upload a file. The change event will dispatch the fromFileUploadActions.UploadRequest() action</li><li>A progress percentage to connected to the fromFileUploadSelectors.selectUploadFileProgress selector for real-time progress</li><li>A Cancel UPload button to dispatch the fromFileUploadActions.UploadCancelRequest() action</li><li>An Upload Another File button to dispatch the fromFileUploadActions.UploadResetRequest() action and allow for a new file upload</li></ul><blockquote><em>This would be a good scenario to create a connected container with a dumb component, but for the brevity of this article I will show these combined as one. In the example repository, I will show both scenarios.</em></blockquote><h3>Generate the component</h3><blockquote><a href="https://angular.io/cli"><em>Click here</em></a><em> for more details on using the powerful Angular CLI</em></blockquote><p>$ ng g component upload-file</p><blockquote><em>For simplicity of this article we will just display the progress percentage, this could easily be adapted to hook into the </em><em>value property of a progress bar control, like the Angular Material library provides.</em></blockquote><h4>Inject the Store</h4><p>We need to wire-up our store into this component for use. Let’s start by injecting the store into the constructor. The finished constructor should look something like this:</p><pre>...<br>constructor(private store$: Store&lt;fromFileUploadState.State&gt;) {}</pre><h4>Wire-up our selectors from state</h4><p>Let’s create six (6) public fields on the component. A good practice is to place $ as a suffix so that you know these are Observable and must be subscribed to in the template.</p><pre>completed$: Observable&lt;boolean&gt;;<br>progress$: Observable&lt;number&gt;;<br>error$: Observable&lt;string&gt;;<br><br>isInProgress$: Observable&lt;boolean&gt;;<br>isReady$: Observable&lt;boolean&gt;;<br>hasFailed$: Observable&lt;boolean&gt;;</pre><p>Let’s hook these up to the store in our ngOnInit life-cycle hook.</p><pre>ngOnInit() {<br>  this.completed$ = this.store$.pipe(<br>    select(fromFileUploadSelectors.selectUploadFileCompleted)<br>  );<br><br>  this.progress$ = this.store$.pipe(<br>    select(fromFileUploadSelectors.selectUploadFileProgress)<br>  );<br><br>  this.error$ = this.store$.pipe(<br>    select(fromFileUploadSelectors.selectUploadFileError)<br>  );<br><br>  this.isInProgress$ = this.store$.pipe(<br>    select(fromFileUploadSelectors.selectUploadFileInProgress)<br>  );<br><br>  this.isReady$ = this.store$.pipe(<br>    select(fromFileUploadSelectors.selectUploadFileReady)<br>  );<br><br>  this.hasFailed$ = this.store$.pipe(<br>    select(fromFileUploadSelectors.selectUploadFileFailed)<br>  );<br>}</pre><h4>Wire-up our action dispatchers</h4><p>Let’s add uploadFile, resetUpload, and cancelUpload methods to connect our button clicks to dispatch actions in the store.</p><pre>uploadFile(event: any) {<br>  const files: FileList = event.target.files;<br>  const file = files.item(0);<br><br>  this.store$.dispatch(<br>    new fromFileUploadActions.UploadRequestAction({<br>      file<br>    })<br>  );<br><br>  // clear the input form<br>  event.srcElement.value = null;<br>}<br><br>resetUpload() {<br>  this.store$.dispatch(new UploadFileStoreActions.UploadResetAction());<br>}<br><br>cancelUpload() {<br>  this.store$.dispatch(new UploadFileStoreActions.UploadCancelAction());<br>}</pre><h4>Finished Component *.ts file</h4><p>The finished component *.ts file should look similar to the following:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { select, Store } from &#39;@ngrx/store&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import * as fromFileUploadActions from &#39;src/app/upload-file-store/actions&#39;;<br>import * as fromFileUploadSelectors from &#39;src/app/upload-file-store/selectors&#39;;<br>import * as fromFileUploadState from &#39;src/app/upload-file-store/state&#39;;<br><br>@Component({<br>  selector: &#39;app-upload-file&#39;,<br>  templateUrl: &#39;./upload-file.component.html&#39;,<br>  styleUrls: [&#39;./upload-file.component.css&#39;]<br>})<br>export class UploadFileComponent implements OnInit {<br>  completed$: Observable&lt;boolean&gt;;<br>  progress$: Observable&lt;number&gt;;<br>  error$: Observable&lt;string&gt;;<br>  isInProgress$: Observable&lt;boolean&gt;;<br>  isReady$: Observable&lt;boolean&gt;;<br>  hasFailed$: Observable&lt;boolean&gt;;<br><br>  constructor(private store$: Store&lt;fromFileUploadState.State&gt;) {}<br><br>  ngOnInit() {<br>    this.completed$ = this.store$.pipe(<br>      select(fromFileUploadSelectors.selectUploadFileCompleted)<br>    );<br><br>    this.progress$ = this.store$.pipe(<br>      select(fromFileUploadSelectors.selectUploadFileProgress)<br>    );<br><br>    this.error$ = this.store$.pipe(<br>      select(fromFileUploadSelectors.selectUploadFileError)<br>    );<br><br>    this.isInProgress$ = this.store$.pipe(<br>      select(fromFileUploadSelectors.selectUploadFileInProgress)<br>    );<br><br>    this.isReady$ = this.store$.pipe(<br>      select(fromFileUploadSelectors.selectUploadFileReady)<br>    );<br><br>    this.hasFailed$ = this.store$.pipe(<br>      select(fromFileUploadSelectors.selectUploadFileFailed)<br>    );<br>  }<br><br>  uploadFile(event: any) {<br>    const files: FileList = event.target.files;<br>    const file = files.item(0);<br><br>    this.store$.dispatch(<br>      new fromFileUploadActions.UploadRequestAction({<br>        file<br>      })<br>    );<br><br>    // clear the input form<br>    event.srcElement.value = null;<br>  }<br><br>  resetUpload() {<br>    this.store$.dispatch(new fromFileUploadActions.UploadResetAction());<br>  }<br><br>  cancelUpload() {<br>    this.store$.dispatch(new fromFileUploadActions.UploadCancelAction());<br>  }<br>}</pre><p>We are going to add five (5) major parts to our upload file component.</p><h4>Add the input field</h4><p>There is no upload file button, rather we will make use of the built-in input component and hook to the change event. Any time a file is added to the form this event will fire. We also only want to display this form if we are accepting new files to be uploaded, i.e. it has failed or it is ready. We will use the *ngIf structural directive to help here referencing our isReady$ and hasFailed$ observables.</p><pre>&lt;div class=&quot;message&quot; *ngIf=&quot;(isReady$ | async) || (hasFailed$ | async)&quot;&gt;<br>  &lt;input #file type=&quot;file&quot; multiple (change)=&quot;uploadFile($event)&quot; /&gt;<br>&lt;/div&gt;</pre><h4>Add the progress message</h4><p>This message will be displayed when the progress is greater than or equal to 0% and the UploadStatus is Failed. We will use *ngIf to only display if it&#39;s in this state using the isInProgress$ selector value. We will set the text of the progress message to the progress$ selector value.</p><pre>&lt;div class=&quot;message&quot; *ngIf=&quot;(isInProgress$ | async)&quot;&gt;<br>  &lt;div style=&quot;margin-bottom: 14px;&quot;&gt;Uploading... {{ progress$ | async }}%&lt;/div&gt;<br>&lt;/div&gt;</pre><h4>Add the Cancel Upload button</h4><p>This button will utilize the *ngIf to only display if the upload is in progress using the isInProgress$ selector value. The click event will trigger the dispatch of the UploadCancelAction.</p><pre>&lt;div class=&quot;message&quot; *ngIf=&quot;(isInProgress$ | async)&quot;&gt;<br>  &lt;button (click)=&quot;cancelUpload()&quot;&gt;Cancel Upload&lt;/button&gt;<br>&lt;/div&gt;</pre><h4>Add the Reset Upload button</h4><p>This button will utilize the *ngIf to only display if the upload is complete using the completed$ selector value. The click event will trigger the dispatch of the UploadResetAction.</p><pre>&lt;div class=&quot;message&quot; *ngIf=&quot;(completed$ | async)&quot;&gt;<br>  &lt;h4&gt;<br>    File has been uploaded successfully!<br>  &lt;/h4&gt;<br>  &lt;button (click)=&quot;resetUpload()&quot;&gt;Upload Another File&lt;/button&gt;<br>&lt;/div&gt;</pre><h4>Add the Error message</h4><p>This button will utilize the *ngIf to only display if hasFailed$ selector value returns true. The actual error message is pulled from the error$ selector value.</p><pre>&lt;div class=&quot;message error&quot; *ngIf=&quot;(hasFailed$ | async)&quot;&gt;<br>  Error: {{ error$ | async }}<br>&lt;/div&gt;</pre><h4>Finished Component *.html file</h4><pre>&lt;div class=&quot;message&quot; *ngIf=&quot;(isReady$ | async) || (hasFailed$ | async)&quot;&gt;<br>  &lt;input #file type=&quot;file&quot; multiple (change)=&quot;uploadFile($event)&quot; /&gt;<br>&lt;/div&gt;<br><br>&lt;div class=&quot;message&quot; *ngIf=&quot;(isInProgress$ | async)&quot;&gt;<br>  &lt;div style=&quot;margin-bottom: 14px;&quot;&gt;Uploading... {{ progress$ | async }}%&lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div class=&quot;message&quot; *ngIf=&quot;(isInProgress$ | async)&quot;&gt;<br>  &lt;button (click)=&quot;cancelUpload()&quot;&gt;Cancel Upload&lt;/button&gt;<br>&lt;/div&gt;<br><br>&lt;div class=&quot;message&quot; *ngIf=&quot;(completed$ | async)&quot;&gt;<br>  &lt;h4&gt;<br>    File has been uploaded successfully!<br>  &lt;/h4&gt;<br>  &lt;button (click)=&quot;resetUpload()&quot;&gt;Upload Another File&lt;/button&gt;<br>&lt;/div&gt;<br><br>&lt;div class=&quot;message error&quot; *ngIf=&quot;(hasFailed$ | async)&quot;&gt;<br>  Error: {{ error$ | async }}<br>&lt;/div&gt;</pre><h3>Add some styles to our Component *.css file</h3><p>For formatting let’s add a few simple classes to our component stylesheet:</p><pre>.message {<br>  margin-bottom: 15px;<br>}<br><br>.error {<br>  color: red;<br>}</pre><h3>Add the Component to our AppComponent</h3><p>For the purposes of this article we will add our new UploadFileComponent component to our AppComponent. The template will look as follows:</p><p>&lt;app-upload-file&gt;&lt;/app-upload-file&gt;</p><h3>(Bonus Feature) Back-end REST Endpoint</h3><p>For a full mock back-end server checkout my repository <a href="https://github.com/wesleygrimes/aspnetcore-mock-file-upload-server">here</a>.</p><p>For those of you brave souls that have made it this far… You might be asking what the backend API endpoint looks like. Well, here&#39;s an example ASP.NET Core Controller offered free of charge ;-)</p><pre>public class FileController : ControllerBase<br>{<br>    [HttpPost(&quot;&quot;)]<br>    public async Task&lt;IActionResult&gt; Post(List&lt;IFormFile&gt; files)<br>    {<br>        try<br>        {<br>            foreach (var file in files)<br>            {<br>                Console.WriteLine($&quot;Begin Uploaded File: {file.FileName}&quot;);<br><br>                //simulate upload<br>                Task.Delay(5000).Wait();<br><br>                Console.WriteLine($&quot;Finished Uploaded File: {file.FileName}&quot;);<br>            }<br><br>            return Ok();<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest($&quot;Unable to upload file(s).&quot;);<br>        }<br>    }<br>}</pre><h3>GitHub Example Repository</h3><p>I always like to provide working code examples that follow the article. You can find this articles companion application at the following repository:</p><ul><li><a href="https://github.com/wesleygrimes/ngrx-file-upload">github.com/wesleygrimes/ngrx-file-upload</a></li></ul><h3>Conclusion</h3><p>It’s important to remember that I have implemented these best practices in several “real world” applications. While I have found these best practices helpful, and maintainable, I do not believe they are an end-all-be-all solution to your NgRx projects; it’s just what has worked for me. I am curious as to what you all think? Please feel free to offer any suggestions, tips, or best practices you’ve learned when building enterprise Angular applications with NgRx and I will update the article to reflect as such. Happy Coding!</p><p><em>Originally published at </em><a href="https://blog.ag-grid.com/managing-file-uploads-with-ngrx-2/"><em>blog.ag-grid.com</em></a><em> on March 25, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fe07b084c1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/managing-file-uploads-with-ngrx-9fe07b084c1b">Managing File Uploads With NgRx</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Routing — Best Practices for Enterprise Applications]]></title>
            <link>https://medium.com/angular-in-depth/angular-routing-best-practices-for-enterprise-applications-526c603e6513?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/526c603e6513</guid>
            <category><![CDATA[enterprise]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 10:34:51 GMT</pubDate>
            <atom:updated>2020-04-29T21:21:35.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Routing — Best Practices for Enterprise Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6sTa63CidDVx9BET.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*6IEpXt2pnOFstVnH.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><h3>Before We Get Started</h3><p>This article is not intended to be a tutorial on routing in Angular. If you are new to Routing in Angular then I highly recommend you check out one of the the following resources:</p><ul><li><a href="https://bit.ly/2WubqhW">Ultimate Courses</a></li><li><a href="https://angular.io/guide/router">Official Angular Docs</a></li></ul><h3>Background</h3><p>The following represents a pattern that I’ve developed at my day job after building several enterprise Angular applications. While most online tutorials do a great job laying out the fundamentals, I had a hard time locating articles that showed recommended conventions and patterns for large and scalable applications.</p><p>With this pattern you should have a clean and concise organization for all routing related concerns in your applications.</p><h3>Prerequisites</h3><p>For context, this article assumes you are using the following version of Angular:</p><ul><li>Angular v7.2.6</li></ul><h3>Best Practice #1 — Create a top-level Routes array file</h3><blockquote><em>The official </em><a href="https://angular.io/guide/router#refactor-the-routing-configuration-into-a-routing-module"><em>Angular docs recommend</em></a><em> creating a full-blown </em><em>app-routing.module.ts for your top-level routing. I have found this extra layer to be unnecessary in most cases.</em></blockquote><blockquote><em>HOT TIP: Only register top-level routes here, if you plan to implement feature modules, then the child routes would live underneath the respective </em><em>feature.routes.ts file. We want to keep this top-level routes file as clean as possible and follow the component tree structure.</em></blockquote><p>Let’s go with the following approach:</p><ol><li>Create a new file named app.routes.ts in the root src/app directory. This file will hold our top-level Routes array. We will come back later throughout the article and fill this in. For now, let’s scaffold it with the following contents:</li></ol><pre>import { Routes } from &#39;@angular/router&#39;; <br>export const AppRoutes: Routes = [];</pre><p>2. Register AppRoutes in the app.module.ts file.</p><ul><li>Import AppRoutes from app.routes.ts</li><li>Import RouterModule from @angular/router</li><li>Add RouterModule.forRoot(AppRoutes) to your imports array</li></ul><p>Your updated app.module.ts will look similar to the following:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { RouterModule } from &#39;@angular/router&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { AppRoutes } from &#39;./app.routes&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, RouterModule.forRoot(AppRoutes)],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {}</pre><h3>Best Practice #2 — Create a feature-level Routes array file</h3><p>In similar fashion to how we constructed the app.routes.ts we will create a feature.routes.ts to list out the individual routes for this feature module. We want to keep our routes as close to the source as possible. This will be in keeping with a clean code approach, and having a good separation of concerns.</p><ol><li>Create a new file named feature/feature.routes.ts where feature matches the name of your feature.module.ts prefix. This file will hold our feature-level Routes array. Keeping in mind that you would replace Feature with the actual name of your module, let’s scaffold it with the following contents:</li></ol><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const FeatureRoutes: Routes = [];</pre><p>2. Register FeatureRoutes in the feature/feature.module.ts file. We will make use of the RouterModule.forChild import so that these routes are automatically registered with lazy loading.</p><ul><li>Import FeatureRoutes from feature.routes.ts</li><li>Import RouterModule from @angular/router</li><li>Add RouterModule.forChild(FeatureRoutes) to your imports array</li></ul><p>Your updated feature/feature.module.ts will look similar to the following:</p><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule } from &#39;@angular/router&#39;;<br>import { FeatureRoutes } from &#39;./feature.routes&#39;;<br><br>@NgModule({<br>  declarations: [],<br>  imports: [CommonModule, RouterModule.forChild(FeatureRoutes)]<br>})<br>export class FeatureModule {}</pre><p>An example of a feature.routes.ts file with child route(s) may look like the following:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { FeatureOneComponent } from &#39;./feature-one.component&#39;;<br>import { FeatureSpecificCanActivateGuard } from &#39;./_guards&#39;;<br><br>export const FeatureOneRoutes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    component: FeatureOneComponent,<br>    canActivate: [FeatureSpecificCanActivateGuard]<br>  }<br>];</pre><h3>Best Practice #3 — Add Lazy Loaded Features to top-level Routes file</h3><blockquote><em>Lazy loading is the concept of deferring load of code assets (javascript, styles) until the user actually needs to utilize the resources. This can bring large performance increases to perceived load times of your application as the entire code set doesn’t have to download on first paint.</em></blockquote><blockquote><em>Angular provides a nice way to handle this with the </em><em>loadChildren option for a given route. More information can be found in the </em><a href="https://angular.io/guide/router#lazy-loading-route-configuration"><em>official Angular docs</em></a><em>.</em></blockquote><p>Once you’ve created your app.routes.ts and *.routes.ts files, you need to register any feature modules that you want to load lazily.</p><h4>Per Feature Module…</h4><p>Update the AppRoutes array in the app.routes.ts file to include a new route the feature:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const AppRoutes: Routes = [<br>  {<br>    path: &#39;feature&#39;,<br>    loadChildren: &#39;./feature/feature.module#FeatureModule&#39;<br>  }<br>];</pre><p>By adding the above route to the array, when the user requests /feature in the browser, Angular lazy loads the module using the path given and then automatically registers any routes defined in the feature.routes.ts FeatureRoutes array using the RouterModule.forChild import.</p><p>For each additional feature module, you would add another item to the AppRoutes array. If you have multiple features, it might look something like the following:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const AppRoutes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    pathMatch: &#39;full&#39;,<br>    redirectTo: &#39;feature-one&#39;<br>  },<br>  {<br>    path: &#39;feature-one&#39;,<br>    loadChildren: &#39;./feature-one/feature-one.module#FeatureOneModule&#39;<br>  },<br>  {<br>    path: &#39;feature-two&#39;,<br>    loadChildren: &#39;./feature-two/feature-two.module#FeatureTwoModule&#39;<br>  }<br>];</pre><h3>Best Practice #4 — Keep Router Guards Organized</h3><p>Here are a few tips to keep your router guards organized. These are just guidelines, but I have found them to be very helpful.</p><h4>Name Your Guards Well</h4><p>Guards should use the following naming convention:</p><ul><li>File Name: name.function.guard.ts</li><li>Class Name: NameFunctionGuard</li></ul><p>Each part being identified as:</p><ul><li>name - this is the name of your guard. What are you guarding against?</li><li>function - this is the function your guard will be attached to. Angular supports CanActivate, CanActivateChild, CanDeactivate, and Resolve.</li></ul><p>An example of an Auth Guard that is attached to the CanActivate function would be named as follows:</p><ul><li>File Name: auth.can-activate.guard</li><li>Class Name: AuthCanActivateGuard</li></ul><h4>Group under _guards folder (Suggestion)</h4><blockquote>Notice the underscore “_” prefix on the folder, this is just for sorting purposes in the editor. I always want these folders to show at the top. I do the same for _models and _services.</blockquote><blockquote>My recommendation deviates from the <a href="https://angular.io/guide/styleguide#overall-structural-guidelines">official style guide</a>, which recommends a folders-by-feature structure.</blockquote><p>Organize all top-level guards under a folder named src/app/_guards. I have seen apps dump guards in the top level directory and this is messy, especially if you end up with more than a few guards.</p><h4>Use Barrel Exports (Suggestion)</h4><blockquote>The jury is still out on whether or not using barrel exports is officially considered a “best practice” or even supported by the Angular style guide. However, I am a big fan of the clean organization this provides. This method is offered as a suggestion.</blockquote><p>Make sure that src/app/_guards has a nice and clean index.ts barrel export. Barrel exports are simply index.ts files that group together and export all public files from a directory. An example is as follows:</p><pre>export * from &#39;./auth.can-activate.guard&#39;;<br>export * from &#39;./require-save.can-deactivate.guard&#39;;</pre><p>Without Barrel Exporting:</p><pre>import { AuthCanActivateGuard } from &#39;src/app/_guards/auth.can-activate.guard&#39;;<br>import { RequireSaveCanDeactivateGuard } from &#39;src/app/_guards/require-save.can-deactivate.guard&#39;;</pre><p>With Barrel Exporting:</p><pre>import { AuthCanActivateGuard, RequireSaveCanDeactivateGuard } from &#39;src/app/_guards&#39;;</pre><p>An example application with a _guards directory would look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*3s5C5fWhZvSXP100.png" /></figure><h4>Organize Feature-Specific Route Guards</h4><p>If you have guards that are <em>only</em> used in a particular FeatureRoutes array, then store these routes underneath a folder named _guards underneath your feature folder. Make sure to follow the same naming conventions defined above, as well as barrel exporting.</p><ul><li>Place guards under a folder named _guards underneath your feature folder</li><li>Make sure to create a barrel export index.ts for clean importing</li></ul><p>An example feature directory with _guards would look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*FFtIzvWWjssPRctv.png" /></figure><h3>Finished Application Structure</h3><p>A completed application structure should look something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*SVk8FLCbwbnr_rJs.png" /></figure><h3>Example GitHub Repository</h3><p>I have created a demonstration repository on GitHub. Feel free to fork, clone, and submit PRs.</p><p><a href="https://github.com/wesleygrimes/angular-routing-best-practices">wesleygrimes/angular-routing-best-practices</a></p><h3>Conclusion</h3><p>It’s important to remember that I have implemented these best practices in several “real world” applications. While I have found these best practices helpful, and maintainable, I do not believe they are an end-all be-all solution to organizing routes in projects; it’s just what has worked for me. I am curious as to what you all think? Please feel free to offer any suggestions, tips, or best practices you’ve learned when building enterprise Angular applications with routing and I will update the article to reflect as such.</p><p>Happy Coding!</p><p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><p><em>Originally published at </em><a href="https://wesleygrimes.com/angular/2019/02/24/angular-routing-best-practices-for-enterprise-applications.html"><em>wesleygrimes.com</em></a><em> on February 24, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526c603e6513" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/angular-routing-best-practices-for-enterprise-applications-526c603e6513">Angular Routing — Best Practices for Enterprise Applications</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Routing — Best Practices for Enterprise Applications]]></title>
            <link>https://itnext.io/angular-routing-best-practices-for-enterprise-applications-da539e4a6d42?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/da539e4a6d42</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[enterprise]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 10:34:51 GMT</pubDate>
            <atom:updated>2019-04-15T12:43:07.440Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Routing — Best Practices for Enterprise Applications</h3><p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6sTa63CidDVx9BET.jpg" /></figure><h3>Before We Get Started</h3><p>This article is not intended to be a tutorial on routing in Angular. If you are new to Routing in Angular then I highly recommend you check out one of the the following resources:</p><ul><li><a href="https://bit.ly/2WubqhW">Ultimate Courses</a></li><li><a href="https://angular.io/guide/router">Official Angular Docs</a></li></ul><h3>Background</h3><p>The following represents a pattern that I’ve developed at my day job after building several enterprise Angular applications. While most online tutorials do a great job laying out the fundamentals, I had a hard time locating articles that showed recommended conventions and patterns for large and scalable applications.</p><p>With this pattern you should have a clean and concise organization for all routing related concerns in your applications.</p><h3>Prerequisites</h3><p>For context, this article assumes you are using the following version of Angular:</p><ul><li>Angular v7.2.6</li></ul><h3>Best Practice #1 — Create a top-level Routes array file</h3><blockquote><em>The official </em><a href="https://angular.io/guide/router#refactor-the-routing-configuration-into-a-routing-module"><em>Angular docs recommend</em></a><em> creating a full-blown </em><em>app-routing.module.ts for your top-level routing. I have found this extra layer to be unnecessary in most cases.</em></blockquote><p>Let’s go with the following approach:</p><ol><li>Create a new file named app.routes.ts in the root src/app directory. This file will hold our top-level Routes array. We will come back later throughout the article and fill this in. For now, let’s scaffold it with the following contents:</li></ol><blockquote><em>HOT TIP: Only register top-level routes here, if you plan to implement feature modules, then the child routes would live underneath the respective </em><em>feature.routes.ts file. We want to keep this top-level routes file as clean as possible and follow the component tree structure.</em></blockquote><pre>import { Routes } from &#39;@angular/router&#39;; <br>export const AppRoutes: Routes = [];</pre><ol><li>Register AppRoutes in the app.module.ts file.</li></ol><ul><li>Import AppRoutes from app.routes.ts</li><li>Import RouterModule from @angular/router</li><li>Add RouterModule.forRoot(AppRoutes) to your imports array</li></ul><p>Your updated app.module.ts will look similar to the following:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { RouterModule } from &#39;@angular/router&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { AppRoutes } from &#39;./app.routes&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, RouterModule.forRoot(AppRoutes)],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {}</pre><h3>Best Practice #2 — Create a feature-level Routes array file</h3><p>In similar fashion to how we constructed the app.routes.ts we will create a feature.routes.ts to list out the individual routes for this feature module. We want to keep our routes as close to the source as possible. This will be in keeping with a clean code approach, and having a good separation of concerns.</p><ol><li>Create a new file named feature/feature.routes.ts where feature matches the name of your feature.module.ts prefix. This file will hold our feature-level Routes array. Keeping in mind that you would replace Feature with the actual name of your module, let’s scaffold it with the following contents:</li></ol><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const FeatureRoutes: Routes = [];</pre><p>2. Register FeatureRoutes in the feature/feature.module.ts file. We will make use of the RouterModule.forChild import so that these routes are automatically registered with lazy loading.</p><ul><li>Import FeatureRoutes from feature.routes.ts</li><li>Import RouterModule from @angular/router</li><li>Add RouterModule.forChild(FeatureRoutes) to your imports array</li></ul><p>Your updated feature/feature.module.ts will look similar to the following:</p><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule } from &#39;@angular/router&#39;;<br>import { FeatureRoutes } from &#39;./feature.routes&#39;;<br><br>@NgModule({<br>  declarations: [],<br>  imports: [CommonModule, RouterModule.forChild(FeatureRoutes)]<br>})<br>export class FeatureModule {}</pre><p>An example of a feature.routes.ts file with child route(s) may look like the following:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { FeatureOneComponent } from &#39;./feature-one.component&#39;;<br>import { FeatureSpecificCanActivateGuard } from &#39;./_guards&#39;;<br><br>export const FeatureOneRoutes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    component: FeatureOneComponent,<br>    canActivate: [FeatureSpecificCanActivateGuard]<br>  }<br>];</pre><h3>Best Practice #3 — Add Lazy Loaded Features to top-level Routes file</h3><blockquote><em>Lazy loading is the concept of deferring load of code assets (javascript, styles) until the user actually needs to utilize the resources. This can bring large performance increases to perceived load times of your application as the entire code set doesn’t have to download on first paint.</em></blockquote><blockquote><em>Angular provides a nice way to handle this with the </em><em>loadChildren option for a given route. More information can be found in the </em><a href="https://angular.io/guide/router#lazy-loading-route-configuration"><em>official Angular docs</em></a><em>.</em></blockquote><p>Once you’ve created your app.routes.ts and *.routes.ts files, you need to register any feature modules that you want to load lazily.</p><h4>Per Feature Module…</h4><p>Update the AppRoutes array in the app.routes.ts file to include a new route the feature:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const AppRoutes: Routes = [<br>  {<br>    path: &#39;feature&#39;,<br>    loadChildren: &#39;./feature/feature.module#FeatureModule&#39;<br>  }<br>];</pre><p>By adding the above route to the array, when the user requests /feature in the browser, Angular lazy loads the module using the path given and then automatically registers any routes defined in the feature.routes.ts FeatureRoutes array using the RouterModule.forChild import.</p><p>For each additional feature module, you would add another item to the AppRoutes array. If you have multiple features, it might look something like the following:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const AppRoutes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    pathMatch: &#39;full&#39;,<br>    redirectTo: &#39;feature-one&#39;<br>  },<br>  {<br>    path: &#39;feature-one&#39;,<br>    loadChildren: &#39;./feature-one/feature-one.module#FeatureOneModule&#39;<br>  },<br>  {<br>    path: &#39;feature-two&#39;,<br>    loadChildren: &#39;./feature-two/feature-two.module#FeatureTwoModule&#39;<br>  }<br>];</pre><h3>Best Practice #4 — Keep Router Guards Organized</h3><p>Here are a few tips to keep your router guards organized. These are just guidelines, but I have found them to be very helpful.</p><h4>Name Your Guards Well</h4><p>Guards should use the following naming convention:</p><ul><li>File Name: name.function.guard.ts</li><li>Class Name: NameFunctionGuard</li></ul><p>Each part being identified as:</p><ul><li>name - this is the name of your guard. What are you guarding against?</li><li>function - this is the function your guard will be attached to. Angular supports CanActivate, CanActivateChild, CanDeactivate, and Resolve.</li></ul><p>An example of an Auth Guard that is attached to the CanActivate function would be named as follows:</p><ul><li>File Name: auth.can-activate.guard</li><li>Class Name: AuthCanActivateGuard</li></ul><h4>Group under _guards folder</h4><blockquote>Notice the underscore “_” prefix on the folder, this is just for sorting purposes in the editor. I always want these folders to show at the top. I do the same for <em>_models</em> and <em>_services</em>.</blockquote><p>Organize all top-level guards under a folder named src/app/_guards. I have seen apps dump guards in the top level directory and this is messy, especially if you end up with more than a few guards.</p><h4>Use Barrel Exports</h4><blockquote>The jury is still out on whether or not using barrel exports is officially considered a “best practice” or even supported by the Angular style guide. However, I am a big fan of the clean organization this provides. This method is offered as a suggestion.</blockquote><p>Make sure that src/app/_guards has a nice and clean index.ts barrel export. Barrel exports are simply index.ts files that group together and export all public files from a directory. An example is as follows:</p><pre>export * from &#39;./auth.can-activate.guard&#39;;<br>export * from &#39;./require-save.can-deactivate.guard&#39;;</pre><p>Without Barrel Exporting:</p><pre>import { AuthCanActivateGuard } from &#39;src/app/_guards/auth.can-activate.guard&#39;;<br>import { RequireSaveCanDeactivateGuard } from &#39;src/app/_guards/require-save.can-deactivate.guard&#39;;</pre><p>With Barrel Exporting:</p><pre>import { AuthCanActivateGuard, RequireSaveCanDeactivateGuard } from &#39;src/app/_guards&#39;;</pre><p>An example application with a _guards directory would look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*3s5C5fWhZvSXP100.png" /></figure><h4>Organize Feature-Specific Route Guards</h4><p>If you have guards that are <em>only</em> used in a particular FeatureRoutes array, then store these routes underneath a folder named _guards underneath your feature folder. Make sure to follow the same naming conventions defined above, as well as barrel exporting.</p><ul><li>Place guards under a folder named _guards underneath your feature folder</li><li>Make sure to create a barrel export index.ts for clean importing</li></ul><p>An example feature directory with _guards would look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*FFtIzvWWjssPRctv.png" /></figure><h3>Finished Application Structure</h3><p>A completed application structure should look something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*SVk8FLCbwbnr_rJs.png" /></figure><h3>Example GitHub Repository</h3><p>I have created a demonstration repository on GitHub. Feel free to fork, clone, and submit PRs.</p><p><a href="https://github.com/wesleygrimes/angular-routing-best-practices">wesleygrimes/angular-routing-best-practices</a></p><h3>Conclusion</h3><p>It’s important to remember that I have implemented these best practices in several “real world” applications. While I have found these best practices helpful, and maintainable, I do not believe they are an end-all be-all solution to organizing routes in projects; it’s just what has worked for me. I am curious as to what you all think? Please feel free to offer any suggestions, tips, or best practices you’ve learned when building enterprise Angular applications with routing and I will update the article to reflect as such.</p><p>Happy Coding!</p><p><em>Originally published at </em><a href="https://wesleygrimes.com/angular/2019/02/24/angular-routing-best-practices-for-enterprise-applications.html"><em>wesleygrimes.com</em></a><em> on February 24, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da539e4a6d42" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/angular-routing-best-practices-for-enterprise-applications-da539e4a6d42">Angular Routing — Best Practices for Enterprise Applications</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular courses for you and your team, a review of Ultimate Courses]]></title>
            <link>https://itnext.io/angular-courses-for-you-and-your-team-a-review-of-ultimate-courses-96b5c336d724?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b5c336d724</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[courses-and-training]]></category>
            <category><![CDATA[training]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 10:34:51 GMT</pubDate>
            <atom:updated>2019-02-27T07:56:33.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-z4KqFcIUey4l6dqcXCaQ.jpeg" /></figure><p>As a senior developer in a small-to-medium sized software firm, I am often tasked with training new developers, or seasoned developers in new technologies. I am always on the lookout for ways to ease the burden and standardize the process for all parties involved.</p><p>One-on-one training and instructor-led training sessions are great, but not everyone has the resources to do this, and often times our current workloads and “deliverables” prevent us from setting aside a week (or more) to devote to training on new topics. Most of you reading this are well aware of the mainstream online training offerings that exist. <a href="https://pluralsight.com/">Pluralsight</a> and <a href="http://lynda.com/">Lynda </a>come to mind.</p><p>While these are fantastic resources, it’s often hard to find Angular training courses that teach on the latest and greatest versions of front-end libraries and frameworks. In this article, I will explore, <a href="https://bit.ly/2WubqhW"><strong><em>Ultimate Courses</em></strong></a>, the offerings created and curated by <a href="https://toddmotto.com/">Todd Motto</a> (Google Developer Expert and Angular extraordinaire).</p><h3>Let’s Review The Packages</h3><p>For Angular development, <a href="https://bit.ly/2WubqhW">Ultimate Courses</a> offers two packages to choose from: <a href="https://bit.ly/2WubqhW"><strong>Angular Kickstart Package</strong></a> and <a href="https://bit.ly/2WubqhW"><strong>Angular Ultimate Package</strong></a>. Let’s quickly review the differences.</p><h4><a href="https://bit.ly/2WubqhW">Angular Kickstart Package</a></h4><p>If your team has previous TypeScript experience, then this is the package I would recommend. It includes:</p><ul><li>A<em>ngular Fundamentals</em></li><li>A<em>ngular Pro</em></li></ul><h4><a href="https://bit.ly/2WubqhW">Angular Ultimate Package</a></h4><p>Learning Angular, for most developers, is not just as simple as learning the frameworks features, conventions and tooling. For most, it requires getting up to speed on <a href="http://www.typescriptlang.org/">TypeScript</a>, a powerful, typed superset of JavaScript. Teaching developers TypeScript is a must for any online solution that I recommend, and thankfully Ultimate Courses’ <a href="https://bit.ly/2WubqhW"><strong>Angular Ultimate Package</strong></a><strong> </strong>has you covered here. It includes:</p><ul><li><em>Angular Fundamentals</em></li><li><em>Angular Pro</em></li><li><em>TypeScript Basics</em></li><li><em>TypeScript Masterclass</em></li><li><em>NGRX Store + Effects</em></li></ul><h4>Individual Courses Available</h4><p>Courses can be purchased in packages as stated above, however, they can also be purchased individually as needed which may make sense for some scenarios.</p><h4>Team Licensing Available</h4><p>If you are working with a team of developers, Ultimate Courses offers user licensing with discounts as the user count grows. This is a great option for teams of developers learning Angular.</p><h3>Angular Fundamentals</h3><p>This course starts out from the high-level and slowly dives deeper into the basic building blocks of an Angular single page application. The content is separated into the following sections:</p><ul><li>Architecture, setup, source files</li><li>ES5 to ES6 and TypeScript refresher</li><li>Getting started</li><li>Template fundamentals</li><li>Rendering flows</li><li>Component Architecture and Feature Modules</li><li>Services, Http and Observables</li><li>Template-driven Forms, Inputs and Validation</li><li>Component Routing</li></ul><p>I won’t dive too deep into each these sections, but I will say for an introductory course, this offering does a fantastic job of giving you just enough information to be dangerous (in a good way), while not overwhelming first-time Angular developers.</p><h3>Angular Pro</h3><p>This course takes the concepts learned in Angular Fundamentals and goes deep, way deep. The topics covered in this course are vital to learn as any Angular app that grows in complexity will almost always need to handle these situations. I appreciate Todd’s attention to detail. Topics covered include:</p><ul><li>Advanced Components — including dynamic component creation</li><li>Directives</li><li>Pipes</li><li>Reactive Forms — This is a good one as the best practice for Angular forms now-a-days is considered Reactive Forms.</li><li>Routing — this includes a nice deep drive into lazy loading modules, a method to speed up initial load times of large applications</li><li>Unit Testing — A must have for distributed teams and complex applications. Todd walks through need-to-know topics around unit testing with built-in Angular tooling.</li><li>Dependency Injection and Zones</li><li>Statement Management with Rx — although I recommend <a href="http://ngrx.io/">NgRx</a></li></ul><h3>TypeScript Basics</h3><p>This course is an introduction to <a href="https://typescriptlang.org/">TypeScript</a>. Developers coming from C# will appreciate this course in particular. In addition, this course can be purchased separately from the <a href="https://platform.ultimatecourses.com/purchase?product_id=869475&amp;affcode=76683_ttll_neb&amp;affcode=76683_ttll_neb">package</a> if you are building with TypeScript. Topics include:</p><ul><li>Overview, setup and source files</li><li>ES6/7 and TypeScript</li><li>Primitive Types</li><li>Special Types</li><li>Type Aliases and Assertions</li><li>Diving into Interfaces</li><li>Classes, Properties and Inheritance</li></ul><h3>TypeScript Masterclass</h3><p>Just as with any language, there are folks that use the basics and are off to the races. There are some cases, however, where you need to dig deep and really understand what’s happening. If you are building Angular or NodeJS libraries, then this course is probably for you. Topics include:</p><ul><li>Understanding and Typing “this”</li><li>Type Queries</li><li>Mapped Types</li><li>Exploring Type Guards</li><li>Advanced Types and Practices</li><li>Generics and Overloads</li><li>Exploring Enums</li><li>Declaration Files</li><li>tsconfig and Compiler Options</li></ul><h3>NGRX Store + Effects</h3><blockquote>Personally, I have been using NgRx for a long time. I no longer build Angular applications without it! So for me, I was very curious to learn how Todd explains this topic. Redux is a complicated pattern for first-time developers to grasp, but it really is a must for creating quality applications.</blockquote><p>In the Angular realm, the Redux pattern is implemented in several libraries, the most popular being NgRx and NGXS. For those of you new to Redux, redux is a pattern for managing global state in an application. It was originally developed at Facebook, and since has taken off and is widely used through most modern front-end frameworks. NgRx is, by far, the most widely used Angular redux library. As such, Ultimate Courses has chosen to focus it’s offerings on NgRx. As we focus on this course, I must say upfront, I was pleasantly surprised and impressed with Todd’s approach to teaching NgRx. The course has been so well received, in fact, that even Mike Ryan (NgRx Core Team/Google Developer Expert) recommends this course as the best way to get started!</p><h4>Course Walkthrough</h4><p>The course starts out by walking through what exactly state management is, how redux accomplishes that, and how JavaScript presents challenges with mutation.</p><p>Once you have grasped the concept of state management using the Redux pattern, the course then has you build your very own vanilla Redux store using plain TypeScript. Realizing then, that NgRx is built on top of these concepts, it’s an easy transfer into learning NgRx.</p><p>After having built a vanilla redux store, the course then walks through the process of setting up a store using the tools provided by NgRx. The course walks you through creating actions, reducers, selectors, effects. The course then walks through the process of structuring lists of entities using the Entity pattern.</p><p>Even folks with some NgRx experience will find this course helpful as it does a deep-dive into more advanced concepts like routing with the store, preloading state, and unit testing your NgRx store.</p><p>Below is a detailed list of the topics covered in this course:</p><ul><li>Redux Architecture</li><li>Writing our own Redux Store</li><li>Architecture: ngrx/store and components</li><li>Core Essentials</li><li>Effects and Entities</li><li>Router State Composition</li><li>Extending our State Tree</li><li>Entity patterns, CRUD operations</li><li>Routing via Dispatch</li><li>State preload and protection via Guards</li><li>Observables and Change Detection</li><li>Unit Testing</li></ul><h3>Conclusion</h3><p>After taking these courses, and comparing other available options, I can safely recommend the <a href="https://bit.ly/2WubqhW">Angular Ultimate Package</a> for teams looking to get into Angular Enterprise development. Todd’s down-to-earth approach of explaining complex concepts, makes these courses both fun and educational. As an added bonus, Todd does the voice-overs himself so you get to learn Angular with a British accent. Win-Win-Win.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*PcWUr-bbhYwJxtg234hfvQ.jpeg" /></figure><h3>More Information on Ultimate Courses</h3><p><a href="https://ultimatecourses.com/?ref=76683_ttll_neb">Ultimate Courses: Expert online courses in JavaScript, Angular, NGRX and TypeScript</a></p><p><em>Originally published at </em><a href="https://wesleygrimes.com/angular/2019/02/22/angular-courses-for-you-and-your-team-a-review-of-ultimate-courses.html"><em>wesleygrimes.com</em></a><em> on February 22, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b5c336d724" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/angular-courses-for-you-and-your-team-a-review-of-ultimate-courses-96b5c336d724">Angular courses for you and your team, a review of Ultimate Courses</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically Remove All Unused TypeScript Imports in a Project]]></title>
            <link>https://itnext.io/automatically-remove-all-unused-typescript-imports-in-a-project-afd4eb0e84b7?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd4eb0e84b7</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Thu, 14 Feb 2019 19:34:51 GMT</pubDate>
            <atom:updated>2019-04-15T12:43:38.095Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automatically Remove All Unused Imports in a TypeScript Project</h3><p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Be06yPbtk8309Mcq.jpg" /></figure><h3>The Problem</h3><p>Recently, I had a need arise to programatically and recursively traverse through all *.ts files in a given project and remove all unused TypeScript imports. At the time this article was written, there was no way to do this within Visual Studio Code without opening each individual *.ts file and hitting CTRL + Shift + O on Windows/Linux. After some research, and much appreciated help from Twitter colleagues, I found a solution that works. This should work for Angular, React, Vue.js, or any plain TypeScript project.</p><h3>The Solution</h3><p>We will use the tslint command line tool, in conjuction with a the tslint-etc rules, to automatically detect and remove all unused imports in the directory, recursively. If you have a large project, the process can take some time to run. It is important to double-check all files for correctness once the fix process is complete.</p><h4>Install Required Tools</h4><p>Install the follow node packages required to for this process to work.</p><pre>$ npm install -g typescript tslint tslint-etc</pre><h4>Create a temporary tslint config file</h4><p>Create a new file named tslint-imports.jsonin the root of your project. This creates a hyper-focused tslint process that will only check for unused declarations. It is <em>important to note</em> that this will throw tslint errors on unused imports, parameters and variables. We are only using this for the --fix process. As such, the tslint-etc rules only autofix unused imports.</p><p>This file needs the following contents:</p><pre>{<br>  &quot;extends&quot;: [<br>    &quot;tslint-etc&quot;<br>  ],<br>  &quot;rules&quot;: {<br>   &quot;no-unused-declaration&quot;: true<br>  }<br>}</pre><h3>Run the autofix process</h3><p>The following command will traverse, recursively through all *.ts files in the project and remove the unused imports. It save the files automatically in place.</p><p><strong>BE CAREFUL!</strong></p><p>This process is only reversible if you are using a source control solution like git or svn, where you can revert changes.</p><pre>$ tslint --config tslint-imports.json --fix --project .</pre><h3>Double-Check Your Files</h3><p>At this point, I would highly recommend you double-check your files for correctness. This tool worked on all but 2 of my 195 *.ts files. Two of the components were incorrectly updated. I was able to spot this by running an ng build --prod as it was an Angular application. You could run a manual tslint --project . if your project doesn’t use a build tool.</p><h3>Resources</h3><ul><li><a href="https://twitter.com/wesgrimes/status/1096134870726774787">Original Twitter Conversation</a></li><li><a href="https://palantir.github.io/tslint/usage/cli/">TSLint</a></li><li><a href="https://cartant.github.io/tslint-etc/">tslint-etc</a></li></ul><p><em>Originally published at </em><a href="https://wesleygrimes.com/angular/2019/02/14/how-to-use-tslint-to-autoremove-all-unused-imports-in-a-typescript-project.html"><em>wesleygrimes.com</em></a><em> on February 14, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd4eb0e84b7" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/automatically-remove-all-unused-typescript-imports-in-a-project-afd4eb0e84b7">Automatically Remove All Unused TypeScript Imports in a Project</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AOT Friendly Dynamic Content Outlet in Angular]]></title>
            <link>https://medium.com/angular-in-depth/building-an-aot-friendly-dynamic-content-outlet-in-angular-59c1a96171a?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c1a96171a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Mon, 21 Jan 2019 13:45:26 GMT</pubDate>
            <atom:updated>2020-04-29T21:28:45.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*BP6_vVHwGC6Q403DdIn2UQ.png" /><figcaption>Overview — Dynamic Content Outlet</figcaption></figure><p><a href="https://ultimatecourses.com/angular?ref=76683_ttll_neb">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses for individuals and teams.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*_la5LSa0kxarTe8c.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>Have you ever needed to dynamically load content or components in your Angular applications? How about in a way that the built-in structural directives — <em>*ngIf</em> and <em>*ngSwitch — </em>just don’t provide? Are you also in need of the optimization benefits of using Ahead-of-Time compilation?</p><p>Well, I have good news for you…(And no you don’t have to be Chuck Norris!) If you stay tuned, I will help you get a solution up and running that will provide a solid way to choose from and load dynamically, at run-time, a set of predefined modules &amp; components in your application.</p><blockquote>This article is assumes you are building an Angular 6+ application generated using the Angular CLI. For information on using the Angular CLI check out the <a href="https://angular.io/cli#cli-command-reference">official documentation</a>.</blockquote><blockquote>This arose out of a business need for the company that I work for. What’s important to note here is that many articles and examples exist on loading content dynamically in Angular, but none that I found worked reliably when compiling Angular with the ` — prod` or ` — aot` flags enabled. The good news is that what I describe in this article works fantastically with Ahead-of-Time compiling.</blockquote><h3>What We’re Going To Do</h3><p>We’re going to build a special module with a dynamic component outlet that can be included and used anywhere in your application. The only requirement is that you register, upfront, an array mapping your dynamic components to their parent modules. You will also add these modules to the lazyModules property in your angular.json file. By doing so, the compiler will pre-compile these modules. The compiler then splits them off into separate minified chunks and makes them available to the SystemJS loader at runtime, with AOT.</p><h3>Let’s Build Our Dynamic Content Outlet</h3><p>Assuming that you have an existing Angular 6+ CLI generated project let’s run through the following steps to scaffold the necessary parts that make up this new Dynamic Content Outlet.</p><p><strong>Generate the Dynamic Content Outlet Module</strong></p><p>Generate a new module named <strong>DynamicContentOutletModule</strong> by running the following command in your shell of choice:</p><pre>$ ng g m dynamic-content-outlet</pre><p>We will come back later to this module and wire things up.</p><p><strong>Build the Dynamic Content Outlet Registry</strong></p><p>Create a new file underneath the newly created folder src/app/dynamic-content-outlet named dynamic-content-outlet.registry.ts. This will serve as the placeholder for array mapping component name to module path and module name. For now, it will be an empty array as follows.</p><pre>interface RegistryItem {<br>  componentName: string;<br>  modulePath: string;<br>  moduleName: string;<br>}</pre><pre>/**<br>* A registry array of Component Name to details<br>* that must be updated with each new component<br>* that you wish to load dynamically.<br>*/</pre><pre>export const DynamicContentOutletRegistry: RegistryItem[] = [];</pre><p><strong>Build the Dynamic Content Outlet Error Component</strong></p><p>Create a new file underneath the folder <strong><em>src/app/dynamic-content-outlet/dynamic-content-outlet-error.component.ts</em></strong>. This will serve as the component to be rendered anytime an error occurs attempting to load a dynamic component. You can customize the <strong>template</strong> property to use any custom styles or layout that you may have. The <strong>errorMessage</strong> input must stay the same and will be fed with the actual details of the error that occurred while attempting to dynamically render your component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d66aec58c4cf9594aa77aaa7cd24c592/href">https://medium.com/media/d66aec58c4cf9594aa77aaa7cd24c592/href</a></iframe><p><strong>Build the Dynamic Content Outlet Service</strong></p><p>Create a new file underneath the folder src/app/dynamic-content-outlet/dynamic-content-outlet.service.ts</p><ul><li>This service encapsulates the logic that loads dynamic components using SystemJS and renders them into the Dynamic Content Outlet.</li><li>It uses the DynamicContentOutletRegistry to lookup the module by componentName.</li><li>It also makes use of a new static property that we will add later on to each module we wish to dynamically load named dynamicComponentsMap. This allows us to get the type literal for the given componentName so that the resolveComponentFactory can instantiate the correct component. You might ask why we didn’t just add a fourth property to the DynamicContentOutletRegistry, well this is because if we import the type in the registry, then it defeats the purpose of lazy loading these modules as the the type will be included in the main bundle.</li><li>If an error occurs, a DynamicContentOutletErrorComponent is rendered instead with the error message included.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634c2fe3d4950c3791bae93178e09656/href">https://medium.com/media/634c2fe3d4950c3791bae93178e09656/href</a></iframe><p><strong>Build the Dynamic Content Outlet Component</strong></p><p>Create a new file underneath the folder src/app/dynamic-content-outlet/dynamic-content-outlet.component.ts. This component takes an input property named componentName that will call the DynamicContentOutletService.GetComponent method passing into it componentName. The service then returns an instance of that rendered and compiled component for injection into the view. The service returns an error component instance if the rendering fails for some reason. The component listens for changes via the ngOnChanges life-cycle method. If the @Input() componentName: string; is set or changes it automatically re-renders the component as necessary. It also properly handles destroying the component with the ngOnDestroy<strong><em> </em></strong>life-cycle method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fb804d81b1f99c87c92215e18186f31/href">https://medium.com/media/4fb804d81b1f99c87c92215e18186f31/href</a></iframe><p><strong>Finish Wiring Up Parts To The Dynamic Content Outlet Module</strong></p><p>Make sure your src/app/dynamic-content-outlet/dynamic-content-outlet.module.ts file looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e3e7696adcabc9946f66d4296629a6/href">https://medium.com/media/14e3e7696adcabc9946f66d4296629a6/href</a></iframe><h3>Let’s Use Our New Dynamic Content Outlet</h3><p>Phew! Take a deep breath and grab a cup of coffee (french press fair trade organic dark roast). The hard work is behind you. Next we will go through the process of actually putting this new module into play!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BhahXd-DWmGj_n-mhP-gA.jpeg" /></figure><p>For any component that you would like dynamically rendered you need to do the following four steps. <strong><em>These steps must be followed exactly.</em></strong></p><h4>1. Prepare your module for dynamic import</h4><ul><li>Confirm that the component is listed in the entryComponents array in the module that the component is a part of.</li><li>Add to the module, a new static property called dynamicComponentsMap. This allows us to get the type literal for the given componentName so that the resolveComponentFactory can instantiate the correct component.</li></ul><blockquote>You might ask why we didn’t just add a fourth property to the <em>DynamicContentOutletRegistry</em> named <em>componentType</em>; well this is because if we import the type in the registry, then it defeats the purpose of lazy loading these modules as the the type will be included in the main bundle.</blockquote><p>A prepared module might look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d69d43358de7338ab3886ac0e1e9229/href">https://medium.com/media/3d69d43358de7338ab3886ac0e1e9229/href</a></iframe><h4>2. Add your dynamic component(s) to the registry</h4><p>For any component that you would like dynamically rendered, add a new entry to the DynamicContentOutletRegistry array in src/app/dynamic-content-outlet/dynamic-content-outlet.registry.ts.</p><p>The following properties must be filled out:</p><ul><li><strong>componentName</strong>: This should match exactly the name of the Component you wish to load dynamically.</li><li><strong>modulePath</strong>: The absolute path to the module containing the component you wish to load dynamically. This is only the path to the module and does NOT include moduleName after a #.</li><li><strong>moduleName</strong>: This is the exact name of the module.</li></ul><p><strong>Example Component Mapping</strong></p><pre>{<br>  componentName: &#39;MySpecialDynamicContentComponent&#39;,<br>  modulePath: &#39;src/app/my-special-dynamic-content/my-special-dynamic-content.module&#39;,<br>  moduleName: &#39;MySpecialDynamicContentModule&#39;<br>},</pre><h4>3. Add your dynamic modules to the lazyModules array</h4><p>In your angular.json update the projects &gt; ** &gt; architect &gt; build &gt; options &gt; lazyModules array and add an item for each module that you added to the registry in order for the Angular AOT compiler to detect and pre-compile your dynamic modules. If you have multiple projects in a folder, make sure you add this for the correct project you are importing and using dynamic modules in. The updated file will look similar to this:</p><pre>{<br>  ...<br>  &quot;projects&quot;: {<br>    &quot;angular-dynamic-content&quot;: {<br>      ...<br>      &quot;architect&quot;: {<br>        &quot;build&quot;: {<br>          &quot;builder&quot;: &quot;@angular-devkit/build-angular:browser&quot;,<br>          &quot;options&quot;: {<br>            ...<br>            &quot;lazyModules&quot;: [&quot;src/app/my-special-dynamic-content/my-special-dynamic-content.module&quot;]<br>          },<br>        }<br>      }<br>    }<br>  }<br>}</pre><h4>Wire up the Dynamic Content Outlet Module</h4><p>Up to this point you have created your dynamic content outlet module and registered your components to be available in the outlet. The last thing we need to do is wire up our new DynamicContentOutletModule<strong> </strong>to be used in our application. In order to do so you need to:</p><p>1. Add your new DynamicContentOutletModule to the imports array of any feature module or the main AppModule of your Angular application.</p><p><strong>Example of addition to the `imports` array</strong></p><pre>@NgModule({<br>...<br>imports: [<br>   ...<br>   DynamicContentOutletModule<br>  ],<br>  ...<br>})</pre><pre>export class AppModule {}</pre><p>2. Add the following tag to the template of the parent component that you would like to render the dynamic content in:</p><pre>&lt;app-dynamic-content-outlet [componentName]=&quot;&#39;MyComponent&#39;&quot;&gt;<br>&lt;/app-dynamic-content-outlet&gt;</pre><p>This is very similar in nature to Angular’s built-in &lt;router-outlet&gt;/&lt;/router-outlet&gt; tag.</p><p>3. Happy ng serve --proding!</p><h3>Conclusion</h3><p>Hopefully you have found this solution helpful. Here is the full GitHub repository example for you to clone and play around with. PR’s are welcome, appreciated, encouraged and accepted!</p><h4>Real-World Complex Example</h4><p>If you are interested in a more in-depth real-world example, then check out the Github Repository which will demonstrate the following:</p><ul><li>Dynamic modules with multiple components</li><li>Demonstrating the use of on-the-fly component changes</li><li>Demonstrating that the scoped styles are loaded dynamically for each component</li></ul><p><strong>GitHub Repository Example</strong></p><p><a href="https://github.com/wesleygrimes/angular-dynamic-content">wesleygrimes/angular-dynamic-content</a></p><h3>Additional Resources</h3><p>I would highly recommend enrolling in the Ultimate Angular courses. It is well worth the money and I have used it as a training tool for new Angular developers. Follow the link below to signup.</p><p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><p><strong>Special Thanks</strong></p><p>I want to take a moment and thank all those I was able to glean this information from. I did not come up with all this on my own, but I was able to get a working solution by combining parts from each of these articles!</p><ul><li><a href="https://blog.angularindepth.com/dynamically-loading-components-with-angular-cli-92a3c69bcd28">Dynamically Loading Components with Angular CLI</a></li><li><a href="https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e">Here is what you need to know about dynamic components in Angular</a></li><li><a href="https://netbasal.com/the-need-for-speed-lazy-load-non-routable-modules-in-angular-30c8f1c33093">The Need for Speed: Lazy Load Non-Routable Modules in Angular 🏎</a></li></ul><p>Also, a huge thank you to Medium reader ivanwonder and Github user Milan Saraiya for pointing this out and providing a fork example of resolution.</p><ul><li><a href="https://twitter.com/ivanwond">ivanwonder (@ivanwond) | Twitter</a></li><li><a href="https://github.com/milansar">milansar - Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c1a96171a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/building-an-aot-friendly-dynamic-content-outlet-in-angular-59c1a96171a">Building an AOT Friendly Dynamic Content Outlet in Angular</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AOT Friendly Dynamic Content Outlet in Angular]]></title>
            <link>https://itnext.io/building-an-aot-friendly-dynamic-content-outlet-in-angular-c2790195cb94?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2790195cb94</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Fri, 18 Jan 2019 22:16:13 GMT</pubDate>
            <atom:updated>2019-04-15T12:44:21.085Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*BP6_vVHwGC6Q403DdIn2UQ.png" /><figcaption>Overview — Dynamic Content Outlet</figcaption></figure><p>Have you ever needed to dynamically load content or components in your Angular applications? How about in a way that the built-in structural directives — <em>*ngIf</em> and <em>*ngSwitch — </em>just don’t provide? Are you also in need of the optimization benefits of using Ahead-of-Time compilation?</p><p>Well, I have good news for you…(And no you don’t have to be Chuck Norris!) If you stay tuned, I will help you get a solution up and running that will provide a solid way to choose from and load dynamically, at run-time, a set of predefined modules &amp; components in your application.</p><blockquote>This article is assumes you are building an Angular 6+ application generated using the Angular CLI. For information on using the Angular CLI check out the <a href="https://angular.io/cli#cli-command-reference">official documentation</a>.</blockquote><blockquote>This arose out of a business need for the company that I work for. What’s important to note here is that many articles and examples exist on loading content dynamically in Angular, but none that I found worked reliably when compiling Angular with the ` — prod` or ` — aot` flags enabled. The good news is that what I describe in this article works fantastically with Ahead-of-Time compiling.</blockquote><h3>What We’re Going To Do</h3><p>We’re going to build a special module with a dynamic component outlet that can be included and used anywhere in your application. The only requirement is that you register, upfront, an array mapping your dynamic components to their parent modules. You will also add these modules to the lazyModules property in your angular.json file. By doing so, the compiler will pre-compile these modules. The compiler then splits them off into separate minified chunks and makes them available to the SystemJS loader at runtime, with AOT.</p><h3>Let’s Build Our Dynamic Content Outlet</h3><p>Assuming that you have an existing Angular 6+ CLI generated project let’s run through the following steps to scaffold the necessary parts that make up this new Dynamic Content Outlet.</p><p><strong>Generate the Dynamic Content Outlet Module</strong></p><p>Generate a new module named <strong>DynamicContentOutletModule</strong> by running the following command in your shell of choice:</p><pre>$ ng g m dynamic-content-outlet</pre><p>We will come back later to this module and wire things up.</p><p><strong>Build the Dynamic Content Outlet Registry</strong></p><p>Create a new file underneath the newly created folder src/app/dynamic-content-outlet named dynamic-content-outlet.registry.ts. This will serve as the placeholder for array mapping component name to module path and module name. For now, it will be an empty array as follows.</p><pre>interface RegistryItem {<br>  componentName: string;<br>  modulePath: string;<br>  moduleName: string;<br>}</pre><pre>/**<br>* A registry array of Component Name to details<br>* that must be updated with each new component<br>* that you wish to load dynamically.<br>*/</pre><pre>export const DynamicContentOutletRegistry: RegistryItem[] = [];</pre><p><strong>Build the Dynamic Content Outlet Error Component</strong></p><p>Create a new file underneath the folder <strong><em>src/app/dynamic-content-outlet/dynamic-content-outlet-error.component.ts</em></strong>. This will serve as the component to be rendered anytime an error occurs attempting to load a dynamic component. You can customize the <strong>template</strong> property to use any custom styles or layout that you may have. The <strong>errorMessage</strong> input must stay the same and will be fed with the actual details of the error that occurred while attempting to dynamically render your component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d66aec58c4cf9594aa77aaa7cd24c592/href">https://medium.com/media/d66aec58c4cf9594aa77aaa7cd24c592/href</a></iframe><p><strong>Build the Dynamic Content Outlet Service</strong></p><p>Create a new file underneath the folder src/app/dynamic-content-outlet/dynamic-content-outlet.service.ts</p><ul><li>This service encapsulates the logic that loads dynamic components using SystemJS and renders them into the Dynamic Content Outlet.</li><li>It uses the DynamicContentOutletRegistry to lookup the module by componentName.</li><li>It also makes use of a new static property that we will add later on to each module we wish to dynamically load named dynamicComponentsMap. This allows us to get the type literal for the given componentName so that the resolveComponentFactory can instantiate the correct component. You might ask why we didn’t just add a fourth property to the DynamicContentOutletRegistry, well this is because if we import the type in the registry, then it defeats the purpose of lazy loading these modules as the the type will be included in the main bundle.</li><li>If an error occurs, a DynamicContentOutletErrorComponent is rendered instead with the error message included.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634c2fe3d4950c3791bae93178e09656/href">https://medium.com/media/634c2fe3d4950c3791bae93178e09656/href</a></iframe><p><strong>Build the Dynamic Content Outlet Component</strong></p><p>Create a new file underneath the folder src/app/dynamic-content-outlet/dynamic-content-outlet.component.ts. This component takes an input property named componentName that will call the DynamicContentOutletService.GetComponent method passing into it componentName. The service then returns an instance of that rendered and compiled component for injection into the view. The service returns an error component instance if the rendering fails for some reason. The component listens for changes via the ngOnChanges life-cycle method. If the @Input() componentName: string; is set or changes it automatically re-renders the component as necessary. It also properly handles destroying the component with the ngOnDestroy<strong><em> </em></strong>life-cycle method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fb804d81b1f99c87c92215e18186f31/href">https://medium.com/media/4fb804d81b1f99c87c92215e18186f31/href</a></iframe><p><strong>Finish Wiring Up Parts To The Dynamic Content Outlet Module</strong></p><p>Make sure your src/app/dynamic-content-outlet/dynamic-content-outlet.module.ts file looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e3e7696adcabc9946f66d4296629a6/href">https://medium.com/media/14e3e7696adcabc9946f66d4296629a6/href</a></iframe><h3>Let’s Use Our New Dynamic Content Outlet</h3><p>Phew! Take a deep breath and grab a cup of coffee (french press fair trade organic dark roast). The hard work is behind you. Next we will go through the process of actually putting this new module into play!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BhahXd-DWmGj_n-mhP-gA.jpeg" /></figure><p>For any component that you would like dynamically rendered you need to do the following four steps. <strong><em>These steps must be followed exactly.</em></strong></p><h4>1. Prepare your module for dynamic import</h4><ul><li>Confirm that the component is listed in the entryComponents array in the module that the component is a part of.</li><li>Add to the module, a new static property called dynamicComponentsMap. This allows us to get the type literal for the given componentName so that the resolveComponentFactory can instantiate the correct component.</li></ul><blockquote>You might ask why we didn’t just add a fourth property to the DynamicContentOutletRegistry named componentType; well this is because if we import the type in the registry, then it defeats the purpose of lazy loading these modules as the the type will be included in the main bundle.</blockquote><p>A prepared module might look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d69d43358de7338ab3886ac0e1e9229/href">https://medium.com/media/3d69d43358de7338ab3886ac0e1e9229/href</a></iframe><h4>2. Add your dynamic component(s) to the registry</h4><p>For any component that you would like dynamically rendered, add a new entry to the DynamicContentOutletRegistry array in src/app/dynamic-content-outlet/dynamic-content-outlet.registry.ts.</p><p>The following properties must be filled out:</p><ul><li><strong>componentName</strong>: This should match exactly the name of the Component you wish to load dynamically.</li><li><strong>modulePath</strong>: The absolute path to the module containing the component you wish to load dynamically. This is only the path to the module and does NOT include moduleName after a #.</li><li><strong>moduleName</strong>: This is the exact name of the module.</li></ul><p><strong>Example Component Mapping</strong></p><pre>{<br>  componentName: &#39;MySpecialDynamicContentComponent&#39;,<br>  modulePath: &#39;src/app/my-special-dynamic-content/my-special-dynamic-content.module&#39;,<br>  moduleName: &#39;MySpecialDynamicContentModule&#39;<br>},</pre><h4>3. Add your dynamic modules to the lazyModules array</h4><p>In your angular.json update the projects &gt; ** &gt; architect &gt; build &gt; options &gt; lazyModules array and add an item for each module that you added to the registry in order for the Angular AOT compiler to detect and pre-compile your dynamic modules. If you have multiple projects in a folder, make sure you add this for the correct project you are importing and using dynamic modules in. The updated file will look similar to this:</p><pre>{<br>  ...<br>  &quot;projects&quot;: {<br>    &quot;angular-dynamic-content&quot;: {<br>      ...<br>      &quot;architect&quot;: {<br>        &quot;build&quot;: {<br>          &quot;builder&quot;: &quot;@angular-devkit/build-angular:browser&quot;,<br>          &quot;options&quot;: {<br>            ...<br>            &quot;lazyModules&quot;: [&quot;src/app/my-special-dynamic-content/my-special-dynamic-content.module&quot;]<br>          },<br>        }<br>      }<br>    }<br>  }<br>}</pre><h4>Wire up the Dynamic Content Outlet Module</h4><p>Up to this point you have created your dynamic content outlet module and registered your components to be available in the outlet. The last thing we need to do is wire up our new DynamicContentOutletModule<strong> </strong>to be used in our application. In order to do so you need to:</p><p>1. Add your new DynamicContentOutletModule to the imports array of any feature module or the main AppModule of your Angular application.</p><p><strong>Example of addition to the `imports` array</strong></p><pre>@NgModule({<br>...<br>imports: [<br>   ...<br>   DynamicContentOutletModule<br>  ],<br>  ...<br>})</pre><pre>export class AppModule {}</pre><p>2. Add the following tag to the template of the parent component that you would like to render the dynamic content in:</p><pre>&lt;app-dynamic-content-outlet [componentName]=&quot;&#39;MyComponent&#39;&quot;&gt;<br>&lt;/app-dynamic-content-outlet&gt;</pre><p>This is very similar in nature to Angular’s built-in &lt;router-outlet&gt;/&lt;/router-outlet&gt; tag.</p><p>3. Happy ng serve --proding!</p><h3>Conclusion</h3><p>Hopefully you have found this solution helpful. Here is the full GitHub repository example for you to clone and play around with. PR’s are welcome, appreciated, encouraged and accepted!</p><h4>Real-World Complex Example</h4><p>If you are interested in a more in-depth real-world example, then check out the Github Repository which will demonstrate the following:</p><ul><li>Dynamic modules with multiple components</li><li>Demonstrating the use of on-the-fly component changes</li><li>Demonstrating that the scoped styles are loaded dynamically for each component</li></ul><p><strong>GitHub Repository Example</strong></p><p><a href="https://github.com/wesleygrimes/angular-dynamic-content">wesleygrimes/angular-dynamic-content</a></p><h3>Additional Resources</h3><p>I would highly recommend enrolling in the Ultimate Angular courses. It is well worth the money and I have used it as a training tool for new Angular developers. Follow the link below to signup.</p><p><a href="https://ultimatecourses.com/?ref=76683_ttll_neb">Ultimate Courses: Expert online courses in JavaScript, Angular, NGRX and TypeScript</a></p><p><strong>Special Thanks</strong></p><p>I want to take a moment and thank all those I was able to glean this information from. I did not come up with all this on my own, but I was able to get a working solution by combining parts from each of these articles!</p><ul><li><a href="https://blog.angularindepth.com/dynamically-loading-components-with-angular-cli-92a3c69bcd28">Dynamically Loading Components with Angular CLI</a></li><li><a href="https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e">Here is what you need to know about dynamic components in Angular</a></li><li><a href="https://netbasal.com/the-need-for-speed-lazy-load-non-routable-modules-in-angular-30c8f1c33093">The Need for Speed: Lazy Load Non-Routable Modules in Angular 🏎</a></li></ul><p>Also, a huge thank you to Medium reader ivanwonder and Github user Milan Saraiya for pointing this out and providing a fork example of resolution.</p><ul><li><a href="https://twitter.com/ivanwond">ivanwonder (@ivanwond) | Twitter</a></li><li><a href="https://github.com/milansar">milansar - Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2790195cb94" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-an-aot-friendly-dynamic-content-outlet-in-angular-c2790195cb94">Building an AOT Friendly Dynamic Content Outlet in Angular</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NgRx — Best Practices for Enterprise Angular Applications]]></title>
            <link>https://itnext.io/ngrx-best-practices-for-enterprise-angular-applications-6f00bcdf36d7?source=rss-9af1d23366c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f00bcdf36d7</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-cli]]></category>
            <dc:creator><![CDATA[Wes]]></dc:creator>
            <pubDate>Wed, 30 May 2018 19:31:47 GMT</pubDate>
            <atom:updated>2019-04-15T12:41:35.013Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><h3>Before We Get Started</h3><p>This article is not intended to be a tutorial on <strong>NgRx</strong>. There are several great resources that currently exist, written by experts much smarter than me. I highly suggest that you take time and learn <strong>NgRx</strong> and the <strong>redux</strong> pattern before attempting to implement these concepts.</p><ul><li><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular — NgRx Store &amp; Effects</a></li><li><a href="https://www.pluralsight.com/courses/play-by-play-angular-ngrx">Pluralsight — Play by Play Angular NgRx</a></li><li><a href="https://medium.com/ngrx">NgRx Blog on Medium.com</a></li><li><a href="https://ngrx.io/docs">NgRx.io Docs</a></li><li><a href="https://ngrx.io/resources">NgRx.io Resources</a></li></ul><h3>Background</h3><p>The following represents a pattern that I’ve developed at my day job after building several enterprise Angular applications using the <strong>NgRx </strong>library. I have found that most online tutorials do a great job of helping you to get your store up and running, but often fall short of illustrating best practices for clean separation of concerns between your store feature slices, root store, and user interface.</p><p>With the following pattern, your root application state, and each slice (property) of that root application state are separated into a <em>RootStoreModule</em> and per feature <em>MyFeatureStoreModule</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heR7Q5p_9a-v4kD1WKg1XQ.png" /></figure><h3>Prerequisites</h3><p>This article assumes that you are building an <a href="https://cli.angular.io/">Angular v6 CLI</a> generated application.</p><h3>Installing NgRx Dependencies</h3><p>Before we get started with generating code, let’s make sure to install the necessary <strong>NgRx </strong>node modules from a prompt:</p><pre>npm install <a href="http://twitter.com/ngrx">@ngrx</a>/{store,store-devtools,entity,effects}</pre><h3>Best Practice #1 — The Root Store Module</h3><p>Create a Root Store Module as a proper Angular <strong>NgModule’s</strong> that bundle together NgRx store logic. Feature store modules will be imported into the Root Store Module allowing for a single root store module to be imported into your application’s main App Module.</p><h4>Suggested Implementation</h4><ol><li>Generate <em>RootStoreModule</em> using the <strong>Angular CLI:</strong></li></ol><pre>ng g module root-store —-flat false —-module app.module.ts</pre><p>2. Generate <em>RootState</em> interface to represent the entire state of your application using the<strong> Angular CLI:</strong></p><pre>ng g interface root-store/root-state</pre><p>This will create an interface named RootState but you will need to rename it to State inside the generated .ts file as we want to later on utilize this as RootStoreState.State</p><p>PLEASE NOTE: You will come back later on and add to this interface each feature module as a property.</p><h3>Best Practice #2 — Create Feature Store Module(s)</h3><p>Create feature store modules as proper Angular NgModule’s that bundle together feature slices of your store, including <em>state</em>, <em>actions</em>, <em>reducer</em>, <em>selectors</em>, and <em>effects</em>. Feature modules are then imported into your <em>RootStoreModule</em>. This will keep your code cleanly organizing into sub-directories for each feature store. In addition, as illustrated later on in the article, public <em>actions</em>, <em>selectors</em>, and <em>state</em> are name-spaced and exported with feature store prefixes.</p><h4>Naming Your Feature Store</h4><p>In the example implementation below we will use the feature name <em>MyFeature</em>, however, this will be different for each feature you generate and should closely mirror the <em>RootState</em> property name. For example, if you are building a blog application, a feature name might be <em>Post</em>.</p><h4>Entity Feature Modules or Standard Feature Modules?</h4><p>Depending on the type of feature you are creating you may or may not benefit from implementing <a href="https://medium.com/ngrx/introducing-ngrx-entity-598176456e15">NgRx Entity</a>. If your store feature slice will be dealing with an array of type then I suggest following the <em>Entity Feature Module </em>implementation below. If building a store feature slice that does not consist of a standard array of type, then I suggest following the <em>Standard Feature Module</em> implementation below.</p><h4>Suggested Implementation — Entity Feature Module</h4><ol><li>Generate <em>MyFeatureStoreModule</em> feature module using the <strong>Angular CLI:</strong></li></ol><pre>ng g module root-store/my-feature-store --flat false --module root-store/root-store.module.ts</pre><p>2. Actions — Create an <em>actions.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/535e6691bd85a5eeb9ea761372fc332e/href">https://medium.com/media/535e6691bd85a5eeb9ea761372fc332e/href</a></iframe><p>3. State — Create a <em>state.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6636678df23e5649b20efe61dfd350b/href">https://medium.com/media/e6636678df23e5649b20efe61dfd350b/href</a></iframe><p>4. Reducer — Create a <em>reducer.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f63ecaff4e7716538849d22c9d24b86/href">https://medium.com/media/6f63ecaff4e7716538849d22c9d24b86/href</a></iframe><p>5. Selectors — Create a <em>selectors.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7cc22f383a5a6e120b0c17f57c9218/href">https://medium.com/media/2e7cc22f383a5a6e120b0c17f57c9218/href</a></iframe><p>6. Effects — Create an <em>effects.ts</em> file in the <em>app/root-store/my-feature-store</em> directory with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c61fca45c7f613165f8ae9ea61c17f16/href">https://medium.com/media/c61fca45c7f613165f8ae9ea61c17f16/href</a></iframe><h4>Suggested Implementation — Standard Feature Module</h4><ol><li>Generate <em>MyFeatureStoreModule</em> feature module using the <strong>Angular CLI:</strong></li></ol><pre>ng g module root-store/my-feature-store --flat false --module root-store/root-store.module.ts</pre><p>2. Actions — Create an <em>actions.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ff119a27f2a6bcf79f66f4070ff3dd/href">https://medium.com/media/d3ff119a27f2a6bcf79f66f4070ff3dd/href</a></iframe><p>3. State — Create a <em>state.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c13df8ada4be4ef684c7a56b7e72550/href">https://medium.com/media/2c13df8ada4be4ef684c7a56b7e72550/href</a></iframe><p>4. Reducer — Create a <em>reducer.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf33b208f9ceb3f0b8cfc2f677f8c57/href">https://medium.com/media/dcf33b208f9ceb3f0b8cfc2f677f8c57/href</a></iframe><p>5. Selectors — Create a <em>selectors.ts</em> file in the <em>app/root-store/my-feature-store</em> directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/553b225f5eff912412c4963ee94778e4/href">https://medium.com/media/553b225f5eff912412c4963ee94778e4/href</a></iframe><p>6. Effects — Create an <em>effects.ts</em> file in the <em>app/root-store/my-feature-store</em> directory with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b31bb1642fcfe93d1e288ce68057849/href">https://medium.com/media/9b31bb1642fcfe93d1e288ce68057849/href</a></iframe><h4>Suggested Implementation — Entity and Standard Feature Modules</h4><p>Now that we have created our feature module, either Entity or Standard typed above, we need to import the parts (state, actions, reducer, effects, selectors) into the Angular NgModule for the feature. In addition, we will create a barrel export in order to make imports in our application components clean and orderly, with asserted name-spaces.</p><ol><li>Update the <em>app/root-store/my-feature-store/my-feature-store.module.ts</em> with the following:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1567542e664c0ec4edbfad3e9dc2481e/href">https://medium.com/media/1567542e664c0ec4edbfad3e9dc2481e/href</a></iframe><p>2. Create an <em>app/root-store/my-feature-store/index.ts</em> <a href="https://twitter.com/toddmotto/status/918818392680824832">barrel export</a>. You will notice that we import our store components and alias them before re-exporting them. This in essence is “name-spacing” our store components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1ef11de96d86a1fd13fddff4e6b0ef3/href">https://medium.com/media/e1ef11de96d86a1fd13fddff4e6b0ef3/href</a></iframe><h3>Best Practice #1 — The Root Store Module (cont.)</h3><p>Now that we have built our feature modules, let’s pick up where we left off in best practice #1 and finish building out our <em>RootStoreModule </em>and <em>RootState.</em></p><h4>Suggested Implementation (cont.)</h4><p>3. Update <em>app/root-store/root-state.ts</em> and add a property for each feature that we have created previously:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33db2d7b18fcccd98c6abf7ad70c5b4a/href">https://medium.com/media/33db2d7b18fcccd98c6abf7ad70c5b4a/href</a></iframe><p>4. Update your <em>app/root-store/root-store.module.ts</em> by importing all feature modules, and importing the following <strong>NgRx</strong> modules: <em>StoreModule.forRoot({})</em> and <em>EffectsModule.forRoot([])</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e9bbeff81b7a092bbeaaee935390c10/href">https://medium.com/media/4e9bbeff81b7a092bbeaaee935390c10/href</a></iframe><p>5. Create an <em>app/root-store/selectors.ts</em> file. This will hold any root state level selectors, such as a Loading property, or even an aggregate Error property:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b87e4a8b504c618431264e363a1396f/href">https://medium.com/media/2b87e4a8b504c618431264e363a1396f/href</a></iframe><p>6. Create an <em>app/root-store/index.ts</em> barrel export for your store with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9cfe90fce71702dfc5efcab0c47b5e1/href">https://medium.com/media/e9cfe90fce71702dfc5efcab0c47b5e1/href</a></iframe><h3>Wiring up the Root Store Module to your Application</h3><p>Now that we have built our Root Store Module, composed of Feature Store Modules, let’s add it to the main <em>app.module.ts </em>and show just how neat and clean the wiring up process is.</p><ol><li>Add <em>RootStoreModule</em> to your application’s <em>NgModule.imports</em> array. Make sure that when you import the module to pull from the barrel export:</li></ol><pre>import { RootStoreModule } from ‘./root-store’;</pre><p>2. Here’s an example <em>container</em> component that is using the store:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b306f45d279886c0bfe5f40ceb7cbe/href">https://medium.com/media/32b306f45d279886c0bfe5f40ceb7cbe/href</a></iframe><h3>Finished Application Structure</h3><p>Once we have completed implementation of the above best practices our Angular application structure should look very similar to something like this:</p><pre>├── app<br> │ ├── app-routing.module.ts<br> │ ├── app.component.css<br> │ ├── app.component.html<br> │ ├── app.component.ts<br> │ ├── app.module.ts<br> │ ├── components<br> │ ├── containers<br> │ │    └── my-feature<br> │ │         ├── my-feature.component.css<br> │ │         ├── my-feature.component.html<br> │ │         └── my-feature.component.ts<br> │ ├── models<br> │ │    ├── index.ts<br> │ │    └── my-model.ts<br> │ │    └── user.ts<br> │ ├── root-store<br> │ │    ├── index.ts<br> │ │    ├── root-store.module.ts<br> │ │    ├── selectors.ts<br> │ │    ├── state.ts<br> │ │    └── my-feature-store<br> │ │    |    ├── actions.ts<br> │ │    |    ├── effects.ts<br> │ │    |    ├── index.ts<br> │ │    |    ├── reducer.ts<br> │ │    |    ├── selectors.ts<br> │ │    |    ├── state.ts<br> │ │    |    └── my-feature-store.module.ts<br> │ │    └── my-other-feature-store<br> │ │         ├── actions.ts<br> │ │         ├── effects.ts<br> │ │         ├── index.ts<br> │ │         ├── reducer.ts<br> │ │         ├── selectors.ts<br> │ │         ├── state.ts<br> │ │         └── my-other-feature-store.module.ts<br> │ └── services<br> │      └── data.service.ts<br> ├── assets<br> ├── browserslist<br> ├── environments<br> │ ├── environment.prod.ts<br> │ └── environment.ts<br> ├── index.html<br> ├── main.ts<br> ├── polyfills.ts<br> ├── styles.css<br> ├── test.ts<br> ├── tsconfig.app.json<br> ├── tsconfig.spec.json<br> └── tslint.json</pre><h3>Fully Working Example — Chuck Norris Joke Generator</h3><p>I have put together a fully working example of the above best practices. It’s a simple Chuck Norris Joke Generator that has uses <em>@angular/material</em> and the <a href="http://www.icndb.com/">http://www.icndb.com/</a> api for data.</p><h4>Github</h4><p><a href="https://github.com/ngHighCountry/angular-ngrx-chuck-norris">ngHighCountry/angular-ngrx-chuck-norris</a></p><h4>Stackblitz</h4><p>You can see the live demo at <a href="https://angular-ngrx-chuck-norris.stackblitz.io/">https://angular-ngrx-chuck-norris.stackblitz.io</a> and here is the <a href="https://stackblitz.com/">Stackblitz</a> editor:</p><p><a href="https://stackblitz.com/edit/angular-ngrx-chuck-norris?embed=1&amp;file=src/app/containers/jokes/jokes.component.ts">angular-ngrx-chuck-norris - StackBlitz</a></p><h3>Conclusion</h3><p>It’s important to remember that I have implemented these best practices in several “real world” applications. While I have found these best practices helpful, and maintainable, I do not believe they are an end-all be-all solution to organizing NgRx projects; it’s just what has worked for me. I am curious as to what you all think? Please feel free to offer any suggestions, tips, or best practices you’ve learned when building enterprise Angular applications with NgRx and I will update the article to reflect as such. Happy Coding!</p><h3>Additional Resources</h3><p>I would highly recommend enrolling in the Ultimate Angular courses, especially the NgRx course. It is well worth the money and I have used it as a training tool for new Angular developers. Follow the link below to signup.</p><p><a href="https://ultimatecourses.com/courses/angular/ref/wes.grimes/">Ultimate Angular™ | Expert-led online Angular and TypeScript training courses</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f00bcdf36d7" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/ngrx-best-practices-for-enterprise-angular-applications-6f00bcdf36d7">NgRx — Best Practices for Enterprise Angular Applications</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>