<?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 John Crowson on Medium]]></title>
        <description><![CDATA[Stories by John Crowson on Medium]]></description>
        <link>https://medium.com/@jtcrowson?source=rss-671829e4d4a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jjgBhbhJeGSUHhCvgwoawA.jpeg</url>
            <title>Stories by John Crowson on Medium</title>
            <link>https://medium.com/@jtcrowson?source=rss-671829e4d4a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:06:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jtcrowson/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 First Look at @ngrx/component]]></title>
            <link>https://medium.com/ngconf/a-first-look-at-ngrx-component-f7fcbf83669a?source=rss-671829e4d4a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fcbf83669a</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[John Crowson]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 20:25:32 GMT</pubDate>
            <atom:updated>2021-09-15T16:08:40.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*myHiBT5RHZT4RwAziPvz8g.png" /></figure><p>At NG Conf 2020, NgRx Core Team member Mike Ryan gave a talk titled “State of NgRx”. In it, Mike introduced the newest section of the NgRx family, NgRx View, which includes the @ngrx/component and @ngrx/router libraries.</p><p>In this blog, we’ll look at <strong>@ngrx/component</strong>, which rethinks how change detection works for Angular applications, and improves the handling of RxJS Observables directly in our Angular templates.</p><h4>Change Detection</h4><p>Out of the box, Angular 9 uses <a href="https://github.com/angular/angular/tree/master/packages/zone.js"><strong>Zone.js</strong></a> to run change detection. If you are curious as to how Zones work or the drawbacks associated with the library’s use, there are plenty of resources available online.</p><p>With NgRx Component, <a href="https://rxjs.dev/">RxJS</a> Observables are used under the hood to determine when to run change detection.</p><h4>Handling Observable in Templates</h4><p>Out of the box, most Angular pipes and directives used in templates, like the async pipe, were not built exclusively for Observables.</p><p>With NgRx Component, an additional pipe and directive are introduced to make it as ergonomic as possible to use Observables directly in Angular templates.</p><p>Let’s see how we can use NgRx Component to eliminate the use of Zones and improve the handling of Observables in Angular templates!</p><h3>Example App with Zones + AsyncPipe</h3><p>To illustrate the use of Zones and the async pipe, let’s look at an example project that binds two Observables directly in a template:</p><ul><li>An Observable&lt;number&gt; (count$) that acts like a counter, emitting an incremented count value every second, starting at zero.</li><li>An Observable&lt;boolean&gt; (isCountEven$) that maps the above Observable to a boolean value, depending on whether the emitted count is an even or odd number.</li></ul><pre>&lt;!-- Below uses Zones for change detection --&gt;<br><strong>&lt;h3&gt;<br>  Counter: {{ count$ | async }}<br>&lt;/h3&gt;</strong></pre><pre>&lt;!-- Want below to show when observable emits for the first time --&gt;<br>&lt;!-- Unfortunately, below also doesn&#39;t show when the isCountEven$ emits a falsy value --&gt;</pre><pre><strong>&lt;p *ngIf=&quot;isCountEven$ | async as isCountEven&quot;&gt;<br>  The count is {{ isCountEven ? &#39;even&#39; : &#39;odd&#39; }}<br>&lt;/p&gt;</strong></pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-1%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fapp.component.html&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-1%3Ffile%3Dsrc%252Fapp%252Fapp.component.html&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/04f231e06a2325c7dee25ddda9e58a49/href">https://medium.com/media/04f231e06a2325c7dee25ddda9e58a49/href</a></iframe><h4>Issues with Zones + AsyncPipe Example</h4><p>The first issue encountered is our use of Zones. Although it might not be visible in a small example, Zones can lead to poor performance as an application scales.</p><p>From the <a href="https://ngrx.io/guide/component/push">NgRx Component Documentation</a>:</p><blockquote>Heavy dynamic and interactive UIs suffer from zones change detection a lot and can lead to bad performance or even unusable applications, but the async pipe does not work in zone-less mode.</blockquote><p>The second issue is the example’s use of the *ngIf directive to only show the paragraph tag after the isEvenCount$ Observable has emitted a value.</p><p>This works because the async pipe emits <strong>null</strong> before an Observable emits the first value, which is considered falsy by the NgIf directive. However, the NgIf directive is also inadvertently hiding the paragraph tag when the Observable returns other intentionally falsy values, in this case, when isEvenCount$ emits false.</p><p><strong>Let’s use NgRx Component to address these issues!</strong></p><h3>Exit Zones</h3><p>Although not practical for most existing Angular applications today, we can remove Zones in our small example application. We can remove Zones by commenting out the import of the library in polyfills.ts and adding the ngZone: &#39;noop&#39; compiler option to our bootstrapModule function in main.ts.</p><pre>platformBrowserDynamic().bootstrapModule(AppModule, {<br>  <strong>ngZone: &#39;noop&#39;</strong><br>}).catch(err =&gt; console.error(err));</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-2%3Fembed%3D1%26file%3Dsrc%252Fmain.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-2%3Ffile%3Dsrc%252Fmain.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa38be7154eb849f95d46a3388a8d15/href">https://medium.com/media/2fa38be7154eb849f95d46a3388a8d15/href</a></iframe><p>You’ll notice this renders our application without a functioning counter, because the AsyncPipe does not work without Zones.</p><h3>Enter NgRx Component</h3><p>We can install @ngrx/component and save it as a dependency using the following command:</p><pre>npm install github:ngrx/component-builds.git --save</pre><p><em>Note that @ngrx/component is an experimental library and is only available through GitHub as of today. Stay tuned for updated </em><a href="https://ngrx.io/guide/component/install"><em>@ngrx/component installation steps</em></a><em>. Because Stackblitz does not currently support GitHub package dependencies, the following Stackblitz examples have the @ngrx/component source code directly contained in the </em><em>src folder.</em></p><p>I also had to disable AOT compilation in my angular.json file to get @ngrx/component to work in theexample app.</p><pre>&quot;aot&quot;: false</pre><p>Finally, let’s declare both the PushPipe and the LetDirective from the NgRx Component library:</p><pre><strong>import { PushPipe, LetDirective } from &#39;@ngrx/component&#39;;</strong></pre><pre>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    <strong>PushPipe,</strong><br>    <strong>LetDirective</strong><br>  ],<br>  // ...<br>})<br>export class AppModule { }</pre><p>Now that we have @ngrx/component installed, let’s revisit our example app.</p><h3>Example App with NgRx Component</h3><h4>Using PushPipe</h4><p>The PushPipe is a direct replacement for the AsyncPipe and schedules change detection when new Observable values are pushed. The PushPipe works with or without Zones.</p><p>In the app.component.html template, we can replace each use of the async pipe directly with the ngrxPush pipe. Our app behavior has now been restored, but without Zones!</p><pre>&lt;h3&gt;<br>  Counter: {{ count$ | <strong>ngrxPush</strong> }}<br>&lt;/h3&gt;</pre><pre>&lt;p *ngIf=&quot;isCountEven$ | <strong>ngrxPush</strong> as isCountEven&quot;&gt;<br>  The count is {{ isCountEven ? &#39;even&#39; : &#39;odd&#39; }}<br>&lt;/p&gt;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-3%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fapp.component.html&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-3%3Ffile%3Dsrc%252Fapp%252Fapp.component.html&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ddf3f30dfaddf1f95e75992ae6854f0/href">https://medium.com/media/6ddf3f30dfaddf1f95e75992ae6854f0/href</a></iframe><h4>Using LetDirective</h4><p>The LetDirective is a structural directive that works similar to the NgIf directive, except the LetDirective is built specifically to unwrap values from an Observable.</p><p>To address the issue of our paragraph tag being hidden when the Observable emits falsy values, we can replace the use of the *ngIf directive with the *ngrxLet directive. Because the LetDirective expects an observable, there is no need to use the AsyncPipe or the PushPipe.</p><pre>&lt;h3&gt;<br>  Counter: {{ count$ | ngrxPush }}<br>&lt;/h3&gt;</pre><pre>&lt;p <strong>*ngrxLet</strong>=&quot;isCountEven$ as isCountEven&quot;&gt;<br>  The count is {{ isCountEven ? &#39;even&#39; : &#39;odd&#39; }}<br>&lt;/p&gt;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-4%3Fembed%3D1%26file%3Dsrc%252Fapp%252Fapp.component.html&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fngrx-component-first-look-4%3Ffile%3Dsrc%252Fapp%252Fapp.component.html&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/02d1d9d6f884acd2f357cd4c40214fe3/href">https://medium.com/media/02d1d9d6f884acd2f357cd4c40214fe3/href</a></iframe><p>Because the LetDirective allows falsy values from our Observable, our application is now behaving as intended. 🎉</p><h3>Conclusion</h3><p>It is awesome to see NgRx’s commitment to providing primitive reactive helpers to enable fully reactive, fully zone-less applications. I encourage you to watch both Mike Ryan and Brandon Roberts talks at NG Conf 2020 to hear more about what NgRx has in active development.</p><p>To read more about @ngrx/component, be sure to check out the work-in-progress documentation available on <a href="https://ngrx.io/">ngrx.io</a>.</p><p>Follow me on Twitter :) <a href="https://twitter.com/john_crowson">@john_crowson</a></p><h3>EnterpriseNG is coming November 4th &amp; 5th, 2021.</h3><p>Come hear top community speakers, experts, leaders, and the Angular team present for 2 stacked days on everything you need to make the most of Angular in your enterprise applications.<br>Topics will be focused on the following four areas:<br> • Monorepos<br> • Micro frontends<br> • Performance &amp; Scalability<br> • Maintainability &amp; Quality<br>Learn more here &gt;&gt; <a href="https://enterprise.ng-conf.org/">https://enterprise.ng-conf.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fcbf83669a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ngconf/a-first-look-at-ngrx-component-f7fcbf83669a">A First Look at @ngrx/component</a> was originally published in <a href="https://medium.com/ngconf">ngconf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MockStore in NgRx v7.0]]></title>
            <link>https://medium.com/ngconf/mockstore-in-ngrx-v7-0-f7803708de4e?source=rss-671829e4d4a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7803708de4e</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[John Crowson]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 18:01:01 GMT</pubDate>
            <atom:updated>2021-09-15T17:51:03.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSA2a12C4smkM7rIP9hLdQ.png" /></figure><p><a href="https://ngrx.io/">NgRx</a> v7.0 included the released of a new @ngrx/store/testing module that features a mock Store to be used in testing NgRx applications. The module was introduced in <a href="https://github.com/ngrx/platform/pull/1027">#1027</a> with some documentation following in <a href="https://github.com/ngrx/platform/pull/1591">#1591</a>.</p><blockquote>Note: You can use this API and functionality in NgRx v5 and v6 using the standalone <a href="https://www.npmjs.com/package/ngrx-mockstore">ngrx-mockstore</a> package.</blockquote><p>Currently, the documentation is light and doesn’t include a complete working code sample. I’ll provide two examples that should help clear things up.</p><h3>Existing: StoreModule</h3><p>It has been possible to condition the NgRx store in a unit test by providing the StoreModule in the testing module configuration. The StoreModule creates a store with the initial state defined in the store’s reducer. To condition the desired state for a given test case, you could have to dispatch several actions.</p><h3>New: MockStore</h3><p>The MockStore class provides a simpler way to condition NgRx state in unit tests. You provide an initial default state, then update the state using setState(&lt;nextState&gt;).</p><p>Let’s see how MockStore can simplify an existing test suite:</p><h4>Testing Auth Guard Example</h4><p>The NgRx <a href="https://github.com/ngrx/platform/tree/master/projects/example-app">example-app</a> contains an AuthGuard that provides us a simple example of using the MockStore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88af8d53f283eb0521fd6db124752c2a/href">https://medium.com/media/88af8d53f283eb0521fd6db124752c2a/href</a></iframe><p>The AuthGuard selects getLoggedIn from the store. If the latest getLoggedIn is true, a LoginRedirect action is dispatched and the function returns false. If the latest getLoggedIn is false, it returns true.</p><p>The existing AuthGuard test uses the StoreModule, which requires the test to dispatch a LoginSuccess action to condition the getLoggedIn selector to return true:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b186576f1a4cdc4001afee57bc89c47/href">https://medium.com/media/7b186576f1a4cdc4001afee57bc89c47/href</a></iframe><p>Let’s refactor the same tests to condition the store’s state without actions using MockStore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a481d915054a3d38b69dfcb243a385ef/href">https://medium.com/media/a481d915054a3d38b69dfcb243a385ef/href</a></iframe><p>Here are the steps:</p><ol><li>Line 6: Declare a MockStore using the same type assertion that is used when declaring the Store in the AuthGuard (fromAuth.State).</li><li>Line 7: Create an initial state conforming to the same state interface that was asserted on line 6. <strong>This will be the default state for all tests.</strong> Since fromAuth.State extends fromRoot.State and our tests only depend on the the user attribute, we can cast everything else.</li><li>Line 19: Provide the MockStore using provideMockStore, passing in the initialState created in the previous step.</li><li>Line 22: Inject the Store inside the test.</li><li>Line 31: To condition a different state, use setState.</li></ol><h4>Testing Effect + withLatestFrom Example</h4><p>I came across <a href="https://github.com/ngrx/platform/issues/414">NgRx issue #414</a> which describes difficulty testing effects that incorporate state using the withLatestFrom operator and the StoreModule.</p><pre>@Effect()<br>example$ = this.actions$.pipe(<br>  ofType(ActionTypes.ExampleAction),<br>  <strong>withLatestFrom(this.store.pipe(<br>    select(fromExample.getShouldDispatchActionOne)<br>  )),</strong><br>  map(([action, shouldDispatchActionOne]) =&gt; {<br>    if (shouldDispatchActionOne) {<br>      return new ActionOne();<br>    } else {<br>      return new ActionTwo();<br>    }<br>  })<br>);</pre><p>The effect’s injected state couldn’t be changed after TestBed.get(&lt;effect&gt;) had been called, making it difficult to test different values selected by getShouldDispatchActionOne in the above snippet. The three common workarounds were:</p><ol><li>Use Jasmine’s SpyOn to mock the return value of state.select(…): spyOn(store, &#39;select&#39;).and.returnValue(of(initialState)). However, select is now an RxJs operator. ❌</li><li>Move TestBed.get(&lt;effect&gt;) from beforeEach into each individual test after the state is conditioned appropriately. 😐</li><li>Provide a mockStore (hey, don’t we have one of those now?). 😀</li></ol><p>Let’s see how we can test effects that use withLatestFrom using the MockStore:</p><p>Let’s add a new effect, addBookSuccess$, to the NgRx example-app’s BookEffects. When a new book is successfully added, we’ll select the books the user now has in their collection the store, then display an alert with a different message depending on the quantity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9bb3294cb2c8f151f353ec1badfedef/href">https://medium.com/media/e9bb3294cb2c8f151f353ec1badfedef/href</a></iframe><p>We can use the MockStore to condition the state, allowing us to test each of the two cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e5a7754a4b4904b7ce2fa7660e699a7/href">https://medium.com/media/7e5a7754a4b4904b7ce2fa7660e699a7/href</a></iframe><p>Here are the steps, similar to those in the AuthGuard Example:</p><ol><li>Line 9: Declare a MockStore using the same type assertion that is used when declaring the Store in the BookEffects (fromBooks.State).</li><li>Line 10: Create an initial state conforming to the same state interface that was asserted on line 9. <strong>This will be the default state for all tests.</strong> Since fromBooks.State extends fromRoot.State and our tests only depend on the the ids attribute, we can cast everything else.</li><li>Line 32: Provide the MockStore using provideMockStore, passing in the initialState created in the previous step.</li><li>Line 38: Inject the Store inside the test.</li><li>Line 59: To condition a different state, use setState.</li></ol><p>Thanks for reading! You can follow me on Twitter <a href="https://twitter.com/john_crowson">@john_crowson</a> :)</p><p>For more Angular goodness, be sure to check out the latest episode of <a href="https://www.spreaker.com/show/angular-show">The Angular Show podcast</a>.</p><h3>EnterpriseNG is coming November 4th &amp; 5th, 2021.</h3><p>Come hear top community speakers, experts, leaders, and the Angular team present for 2 stacked days on everything you need to make the most of Angular in your enterprise applications.<br>Topics will be focused on the following four areas:<br> • Monorepos<br> • Micro frontends<br> • Performance &amp; Scalability<br> • Maintainability &amp; Quality<br>Learn more here &gt;&gt; <a href="https://enterprise.ng-conf.org/">https://enterprise.ng-conf.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7803708de4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ngconf/mockstore-in-ngrx-v7-0-f7803708de4e">MockStore in NgRx v7.0</a> was originally published in <a href="https://medium.com/ngconf">ngconf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filtering Types with Correct Type Inference in RxJs]]></title>
            <link>https://medium.com/ngconf/filtering-types-with-correct-type-inference-in-rxjs-f4edf064880d?source=rss-671829e4d4a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4edf064880d</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[ngconf]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[filters]]></category>
            <dc:creator><![CDATA[John Crowson]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 03:58:15 GMT</pubDate>
            <atom:updated>2021-09-15T18:15:51.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ncdks8aQwtNQ1DpC5CY0Q.png" /></figure><p>A common use of the RxJs filter operator is to only allow or prevent certain types from being passed to the next pipe operator or subscribe function.</p><pre>const scrollEvents$ = router.events.pipe(<br>  filter(event =&gt; event instanceof Scroll)<br>);</pre><p>However, you’ll notice in the above snippet that scrollEvents$ is inferred to be of type Observable&lt;Event&gt; instead of Observable&lt;Scroll&gt;. This inability to correctly infer type is not an issue with RxJs, but rather Typescript (open issues: <a href="https://github.com/Microsoft/TypeScript/issues/10734">#10734</a> and <a href="https://github.com/Microsoft/TypeScript/issues/16069">#16069</a>).</p><h3>Review: Type Checking in Typescript</h3><p>Feel free to skip this section if you are familiar with type checking in Typescript.</p><h4>Primitives</h4><p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a> to check the primitive type:</p><blockquote>typeof is a <em>unary operator</em> that returns a string indicating the type of the unevaluated operand</blockquote><pre>const num = 5;</pre><pre>typeof num; // returns &#39;number&#39;</pre><pre>typeof num === &#39;number&#39; // returns true</pre><h4>Classes</h4><p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a> to check the class type:</p><blockquote>instanceof is a binary operator, accepting an object and a <em>constructor</em>. It returns a boolean <em>indicating whether or not the object has the given constructor in its prototype chain</em>.</blockquote><pre>const toyota = new Car(&quot;Toyota&quot;);</pre><pre>toyota instanceof Car; // returns true</pre><p>Using typeof won’t work:</p><pre>const toyota = new Car(&quot;Toyota&quot;);</pre><pre>typeOf toyota; // returns &#39;object&#39; :(</pre><h4>Interfaces</h4><p>Unfortunately, you can’t use instanceof because interfaces don&#39;t exist at runtime. You also can’t use typeof, because you’ll get back &#39;object&#39;, like with classes.</p><p>You will need to check if a distinct property or function of the interface is defined:</p><pre>interface Fish {<br>  canSwim: boolean;<br>  color: string;<br>}</pre><pre>interface Bird {<br>  canFly: boolean;<br>  wingLength: number;<br>}</pre><pre>const pet = { canSwim: true, color: &#39;green&#39; };</pre><pre>(&lt;Fish&gt;pet).canSwim !== undefined; // returns true, so pet is a fish</pre><h4>User-Defined Type Guards</h4><p>We can utilize a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html">user-defined type guard</a> in Typescript to encapsulate these.</p><blockquote>A type guard is some expression that performs a runtime check that guarantees the type in some scope.</blockquote><pre>function isFish(pet: Fish | Bird): <strong>pet is Fish</strong> {<br>  return (&lt;Fish&gt;pet).canSwim !== undefined;<br>}</pre><pre>const pet = { canSwim: true, color: &#39;green&#39; };</pre><pre>if (isFish(pet)) {<br>  // Type is now inferred to be Fish within the scope<br>  console.log(pet.color);<br>}</pre><p>Note: We could have the pet parameter of isFish accept any, but that would provide more opportunity to provide another interface that also has a canSwim property, causing the type guard to return true incorrectly.</p><h3>Filtering Primitive, Interfaces, and Classes</h3><h4>Option 1: Filter, then Cast</h4><p>The first option is to add an additional map that casts the Event class after the filter:</p><pre>const scrollEvents$ = router.events.pipe(<br>  <strong>filter(event =&gt; event instanceof Scroll),<br>  map(event =&gt; event as Scroll)</strong><br>)<br>.subscribe(event =&gt; console.log(event.position));</pre><p>Now, in subscribe, the event is correctly inferred of type Observable&lt;Scroll&gt;.</p><p>If we want to reuse this same type inferencing filter again, we can create a custom RxJs operator:</p><pre>export function isScrollEvent&lt;Scroll&gt;() {<br>  return (source$: Observable&lt;Event&gt;) =&gt; source$.pipe(<br>    <strong>filter(event =&gt; event instanceof Scroll),<br>    map(event =&gt; event as Scroll)</strong><br>  );<br>}</pre><pre>const scrollEvents$ = router.events.pipe(<br>  <strong>isScrollEvent()</strong><br>).subscribe(event =&gt; console.log(event.position));</pre><p>For primitives or interfaces, we just need to update the filter to use typeof or an undefined check, respectively.</p><h4>Option 2: Define a Type Guard</h4><p>The second option is to define a type guard to correct the type inference:</p><pre>export function inputIsScroll(input: Event): input is Scroll {<br>  return input instanceof Scroll;<br>}</pre><pre>const scrollEvents$ = router.events.pipe(<br>  <strong>filter(inputIsScroll)</strong><br>)<br>.subscribe(event =&gt; console.log(event.position));</pre><p>Now, in subscribe, the event is correctly inferred of type Observable&lt;Scroll&gt;.</p><p>We could abstract this approach further by creating a custom RxJs operator:</p><pre>function inputIsScroll(input: Event): input is Scroll {<br>  return input instanceof Scroll;<br>}</pre><pre>export function isScrollEvent&lt;Scroll&gt;() {<br>  return (source$: Observable&lt;Event&gt;) =&gt; source$.pipe(<br>    filter(inputIsScroll)<br>  );<br>}</pre><pre>const scrollEvents$ = router.events.pipe(<br>  <strong>isScrollEvent()</strong><br>)<br>.subscribe(event =&gt; console.log(event.position));</pre><h3>Filtering Null and Undefined</h3><p>If you search the internet for ways to filter out null and undefined, you’ll likely get one of two suggested solutions:</p><ol><li>filter(Boolean)</li></ol><pre>const source: Observable&lt;string&gt; = of(undefined, &#39;hello&#39;, null);</pre><pre>source.pipe(<strong>filter(Boolean)</strong>).subscribe(str =&gt;<br>  console.log(str.length)<br>);</pre><p>Unfortunately, we lose the type inference, and str is of type any.</p><p>2. filter(x =&gt; x !== null &amp;&amp; x !== undefined)</p><pre>const source: Observable&lt;string&gt; = of(undefined, &#39;hello&#39;, null);</pre><pre>source.pipe(<br>  <strong>filter(str =&gt; str !== null &amp;&amp; str !== undefined)</strong><br>)<br>.subscribe(str =&gt; console.log(str.length));</pre><p>Unfortunately, this does not work if you are using --strictNullChecks.</p><h4>Solution</h4><pre>function inputIsNotNullOrUndefined&lt;T&gt;(input: null | undefined | T): input is T {<br>  return input !== null &amp;&amp; input !== undefined;<br>}</pre><pre>export function isNotNullOrUndefined&lt;T&gt;() {<br>  return (source$: Observable&lt;null | undefined | T&gt;) =&gt;<br>    source$.pipe(<br>      filter(inputIsNotNullOrUndefined)<br>    );<br>}</pre><p>We can now infer the correct type with --strictNullChecks:</p><pre>const source: Observable&lt;string | null | undefined&gt; = of(undefined, &#39;hello&#39;, null);</pre><pre>source.pipe(<br>  <strong>isNotNullOrUndefined()</strong><br>)<br>.subscribe(str =&gt; console.log(str.length));</pre><h3>EnterpriseNG is coming November 4th &amp; 5th, 2021.</h3><p>Come hear top community speakers, experts, leaders, and the Angular team present for 2 stacked days on everything you need to make the most of Angular in your enterprise applications.<br>Topics will be focused on the following four areas:<br> • Monorepos<br> • Micro frontends<br> • Performance &amp; Scalability<br> • Maintainability &amp; Quality<br>Learn more here &gt;&gt; <a href="https://enterprise.ng-conf.org/">https://enterprise.ng-conf.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4edf064880d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ngconf/filtering-types-with-correct-type-inference-in-rxjs-f4edf064880d">Filtering Types with Correct Type Inference in RxJs</a> was originally published in <a href="https://medium.com/ngconf">ngconf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robot Pattern: Maintainable Angular UI Tests]]></title>
            <link>https://medium.com/ngconf/robot-pattern-maintainable-angular-ui-tests-4ca5071f540b?source=rss-671829e4d4a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ca5071f540b</guid>
            <category><![CDATA[robot-pattern]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[protractor]]></category>
            <dc:creator><![CDATA[John Crowson]]></dc:creator>
            <pubDate>Thu, 21 Feb 2019 01:43:53 GMT</pubDate>
            <atom:updated>2021-09-15T18:11:43.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sifv9lDUAyGht3ipoiPY7Q.png" /></figure><h3>Motivation</h3><p>Angular is a fast evolving framework. At a similar pace, there is a growing set of tools to improve our usage of it, including UI tests. Although Protractor is the Angular designated UI testing framework, there has been excitement about Cypress.</p><p>Most development teams who use one UI testing framework wouldn’t dare switch, because it would include a total rewrite of their suite.</p><p><strong>What if we used a UI testing pattern that allowed us to swap frameworks in and out more easily?</strong></p><p>In addition to changing testing frameworks, as a part of the development lifecycle, front-end application are subject to UI layout and functionality changes. One small change could break several different end-to-end tests.</p><p><strong>How do we write UI tests that, for each UI change, only require an update in one place, instead of in every UI test that touches the change?</strong></p><h3>The Robot Testing Pattern</h3><p>The Robot Testing Pattern is a UI testing architecture introduced by <a href="https://jakewharton.com/testing-robots/">Jake Wharton</a>. It promotes the creation of readable, reusable, and maintainable UI tests through abstracting <strong>what</strong> is being tested from <strong>how</strong> it’s being tested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMz0qwPZCnNlRSethuiXwA.png" /><figcaption>The Robot Testing Pattern abstracts <strong>what</strong> is being tested from <strong>how</strong> it’s being tested</figcaption></figure><p>Here’s what our example app functionality looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8G0GxCqmVePZBcfZQjwGw.png" /><figcaption>Clicking “View Less” reduces the table to three rows</figcaption></figure><p>The Robot will provide abstracted methods to interact with the view, making the test definition simple:</p><pre>it(&#39;should shrink to show 3 items when View Less is clicked&#39;, () =&gt; {<br>  listPage.clickViewMoreItemsButton()<br>    .verifyNumberOfItems(5)<br>    .clickViewLessItemsButton()<br>    .verifyNumberOfItems(3);<br>});</pre><p>This is exceptionally<strong> </strong>readable. If we want to test the functionality of clicking “View More” instead, we can reuse the same robot methods.</p><pre>it(&#39;should grow to show 5 items when View More is clicked&#39;, () =&gt; {<br>  listPage.clickViewLessItemsButton()<br>    .verifyNumberOfItems(3)<br>    .clickViewMoreItemsButton()<br>    .verifyNumberOfItems(5);<br>});</pre><p>For each view in our application, we will create a Robot class. It looks like the Builder pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db96a2b31b17592a3118c21749933a72/href">https://medium.com/media/db96a2b31b17592a3118c21749933a72/href</a></iframe><p>If we refactored to use the Cypress UI testing framework, we would only reimplement the Robot methods.</p><p>If we refactored the table to grow and shrink on hover, for example, we would only reimplement the clickViewMoreItemsButton() and clickViewLessItemsButton() Robot methods (along with method renaming).</p><p>The test definitions would remain the same.</p><p>Resources:</p><p><a href="https://jakewharton.com/testing-robots/">Testing Robots - Jake Wharton</a></p><h3>EnterpriseNG is coming November 4th &amp; 5th, 2021.</h3><h4>Come hear top community speakers, experts, leaders, and the Angular team present for 2 stacked days on everything you need to make the most of Angular in your enterprise applications.<br>Topics will be focused on the following four areas:<br> • Monorepos<br> • Micro frontends<br> • Performance &amp; Scalability<br> • Maintainability &amp; Quality<br>Learn more here &gt;&gt; https://enterprise.ng-conf.org/</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ca5071f540b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ngconf/robot-pattern-maintainable-angular-ui-tests-4ca5071f540b">Robot Pattern: Maintainable Angular UI Tests</a> was originally published in <a href="https://medium.com/ngconf">ngconf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing to Angular Material Dialogs]]></title>
            <link>https://medium.com/ngconf/routing-to-angular-material-dialogs-c3fb7231c177?source=rss-671829e4d4a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3fb7231c177</guid>
            <category><![CDATA[dialog]]></category>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[router]]></category>
            <dc:creator><![CDATA[John Crowson]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 21:04:15 GMT</pubDate>
            <atom:updated>2021-09-15T18:24:36.630Z</atom:updated>
            <content:encoded><![CDATA[<p>Many Angular developers chose to use Angular Material because it provides a huge set of components that reduce the complexity of building user experiences. One of my favorites has been the <a href="https://material.angular.io/components/dialog/overview">Dialog component</a>.</p><p>The default functionality provided by Material allows developers to launch a dialog by injecting the MatDialog service in a component’s constructor, then calling the service&#39;s open function, passing in the component to be shown in a dialog. We can also pass data to the dialog component and configure the layout of the dialog:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5398192c2f2d75f01889952f93887d19/href">https://medium.com/media/5398192c2f2d75f01889952f93887d19/href</a></iframe><p>But as users of the web, we expect to be able to navigate to an experience by following a link (in the above example, clicking “Open Dialog” anchor) or by <strong>entering the URL directly</strong>. How can we provide the latter using Material Dialogs?</p><p><em>Example use case: I was to send an email to my online store’s customers with a direct link to a “Add a Payment Account” dialog.</em></p><p>Options:</p><ol><li>Add a query parameter to the parent component’s path, access it using ActivatedRoute, and open the dialog.</li><li>Add a child path to the parent’s route configuration that opens the dialog.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6h_mx0wnG__rH0FJbJSGeA.png" /></figure><p>The first option makes the passing of data between parent and child dialog easy. We can take data from our component and send it to the child dialog component using the open function. The second option makes traditional data passing more difficult, but the difficulty can be mitigated if your application maintains a “global state” (NgRx, for example) where you can access the data. The second option removes most dialog-specific logic from the parent component and into a route configuration, allowing for less code duplication if the dialog will be opened from multiple parents.</p><p>We will base our solutions on the Angular Material Dialog <a href="https://material.angular.io/components/dialog/overview">documentation</a> example, which shows the default functionality. Feel free to get familiar with the example application’s behavior.</p><p>You may follow along using the example <a href="https://stackblitz.com/edit/material-dialog-starter">on StackBlitz</a> (embedded below).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-starter%3Fembed%3D1%26file%3Dapp%252Fdialog-overview-example.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-starter%3Ffile%3Dapp%252Fdialog-overview-example.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b765b2e7894f4b47f1b0f5c8eb41dc/href">https://medium.com/media/63b765b2e7894f4b47f1b0f5c8eb41dc/href</a></iframe><h3>Prerequisite: Add the Router Module</h3><p>In both options, we’ll need to import and configure the <a href="https://angular.io/api/router/RouterModule">Router Module</a> to allow us to define routes.</p><p>In main.ts, add the router configuration for our parent component:</p><pre>import {RouterModule} from &#39;@angular/router&#39;;<br>...</pre><pre>imports: [<br>  ...<br>  RouterModule.forRoot([<br>    {<br>      path: &#39;home&#39;,<br>      component: DialogOverviewExample<br>    },<br>    { <br>      path: &#39;**&#39;, // bonus: all routes not defined forward to /home<br>      redirectTo: &#39;home&#39;<br>    }<br>  ])<br>]</pre><p>Next let’s create a component that will hold our <a href="https://angular.io/api/router/RouterOutlet">router-outlet</a>:</p><pre>import { Component } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;my-app&#39;,<br>  template: `<br>    &lt;div class=&quot;container&quot;&gt;<br>      &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class AppComponent  { }</pre><p>Then declare and bootstrap AppComponent in main.ts, and replace the dialog-overview-example tag with my-app in index.html.</p><p>We can now navigate to our parent component via the path “/home”.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-starter-prereqs%3Fembed%3D1%26file%3Dmain.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-starter-prereqs%3Ffile%3Dmain.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24e809ed2d29c07363323c457815826/href">https://medium.com/media/d24e809ed2d29c07363323c457815826/href</a></iframe><h3>Option 1: Routing by Query Parameter</h3><blockquote>Add a query parameter to the parent component’s path, access it using ActivatedRoute, and then open the dialog.</blockquote><p>We will open the dialog when the user navigates to “/home?dialog=true”.</p><p>In the parent template (dialog-overview-example.html), remove the existing example functionality that opens the dialog by directly calling the openDialog function. Replace it with a routerLink with the defined query parameters:</p><pre>&lt;button mat-raised-button <strong>routerLink=&quot;&quot; [queryParams]=&quot;{dialog: true}&quot;</strong>&gt;Pick one&lt;/button&gt;</pre><p>In the parent component (DialogOverviewExample in dialog-overview-example.ts), subscribe to the <a href="https://angular.io/api/router/ActivatedRoute">ActivatedRoute</a>’s query parameters, and open the dialog if the dialog query parameter exists.</p><pre>export class DialogOverviewExample implements OnDestroy {<br>  animal: string;<br>  name: string;<br>  <strong>routeQueryParams$: Subscription;</strong></pre><pre>  constructor(<br>    public dialog: MatDialog,<br>    <strong>private route: ActivatedRoute</strong><br>  ) {<br>    <strong>this.routeQueryParams$ = route.queryParams.subscribe(params =&gt; {<br>      if (params[&#39;dialog&#39;]) {<br>        this.openDialog();<br>      }<br>    });</strong><br>  }</pre><pre>  ngOnDestroy() {<br>    <strong>this.routeQueryParams$.unsubscribe();</strong><br>  }<br>  ...<br>}</pre><p>Now our dialog opens when the user navigates to “/home?dialog=true”, but it does not return to “/home” after the dialog is closed.</p><p>Remove the query parameter by navigating to the current route without query parameters in the MatDialog afterClosed subscription:</p><pre>constructor(<br>  public dialog: MatDialog,<br>  private route: ActivatedRoute,<br>  <strong>private router: Router</strong><br>) {<br>  ...<br>}<br>openDialog(): void {<br>  const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {<br>    width: &#39;250px&#39;,<br>    data: {name: this.name, animal: this.animal}<br>  });</pre><pre>  dialogRef.afterClosed().subscribe(result =&gt; {<br>    console.log(&#39;The dialog was closed&#39;);<br>    this.animal = result;<br>    <strong>this.router.navigate([&#39;.&#39;], { relativeTo: this.route });</strong><br>  });<br>}</pre><h4>Done!</h4><p>This option is pretty straightforward. As mentioned, a drawback to this option is the amount of dialog-specific code that complicates the parent component. For each parent component, we have to add a query parameter subscription, handle opening the dialog, and handle cleaning up after the dialog is closed.</p><p>Here’s the final product:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-route-dialog-queryparams%3Fembed%3D1%26file%3Dapp%252Fdialog-overview-example.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-route-dialog-queryparams%3Ffile%3Dapp%252Fdialog-overview-example.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c504a699d84ef58d0fd5a3efaa607dc/href">https://medium.com/media/6c504a699d84ef58d0fd5a3efaa607dc/href</a></iframe><h3>Option 2: Routing by Path</h3><blockquote>Add a child path to the parent’s route configuration that opens the dialog.</blockquote><p>We will open the dialog when the user navigates to “/home/dialog”.</p><p>This option is not as straightforward. Where do we call the MatDialog open from? We cannot arbitrarily execute a function from the Route configuration. We’d need to do it from a component or guard.</p><pre><strong>// This is NOT possible with the RouterModule...</strong><br>RouterModule.forRoot([<br>  {<br>    path: &#39;home&#39;,<br>    component: DialogOverviewExample,<br>    children: [<br>      {<br>        <strong>path: &#39;dialog&#39;,<br>        executeFunction: openDialog()</strong><br>      }<br>    ]<br>  },<br>  { path: &#39;**&#39;, redirectTo: &#39;home&#39; }<br>])</pre><p>We can create a dummy component for the path ‘dialog’ that manages opening, closing, and passing data to the dialog. When the dummy component gets initialized on ‘dialog’ navigation, it will open the dialog.</p><p>We’ll call our dummy component DialogEntryComponent:</p><pre>@Component({<br>  template: &#39;&#39;<br>})<br>export class DialogEntryComponent {<br>  constructor(public dialog: MatDialog) {<br>    this.openDialog();<br>  }</pre><pre>  openDialog(): void {<br>    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {<br>      width: &#39;250px&#39;<br>    });</pre><pre>    dialogRef.afterClosed().subscribe(result =&gt; {<br>      console.log(&#39;The dialog was closed&#39;);<br>    });<br>  }<br>}</pre><p>And our simplified DialogOverviewExample:</p><pre>@Component({<br>  selector: &#39;dialog-overview-example&#39;,<br>  templateUrl: &#39;dialog-overview-example.html&#39;,<br>  styleUrls: [&#39;dialog-overview-example.css&#39;]<br>})<br>export class DialogOverviewExample {<br>  <strong>// MatDialog code moved<br>  // open/close handled in DialogEntryComponent</strong><br>}</pre><p>Declare the dummy component and configure the Router Module to load it on ‘dialog’ navigation in main.ts:</p><pre>imports: [<br>  ...<br>  RouterModule.forRoot([<br>    {<br>      path: &#39;home&#39;,<br>      component: DialogOverviewExample,<br>      <strong>children: [<br>        {<br>          path: &#39;dialog&#39;,<br>          component: DialogEntryComponent<br>        }<br>      ]</strong><br>    },<br>    { path: &#39;**&#39;, redirectTo: &#39;home&#39; }<br>  ])<br>],<br>declarations: [<br>  ...<br>  <strong>DialogEntryComponent</strong><br>]</pre><p>In order to provide a launch point for the child route, we’ll need to add a router-outlet to the parent template (dialog-overview-example.html):</p><pre>&lt;ol&gt;<br>  ...<br>&lt;/ol&gt;<br><strong>&lt;router-outlet&gt;&lt;/router-outlet&gt;</strong></pre><p>In the same file, remove the existing example functionality that opens the dialog by directly calling the openDialog function. Replace it with a routerLink to the child component:</p><pre>&lt;button mat-raised-button <strong>routerLink=&quot;dialog&quot;</strong>&gt;Pick one&lt;/button&gt;</pre><p>Now our dialog opens when the user navigates to “/home/dialog”, but it does not return to “/home” after the dialog is closed.</p><p>Navigate back to the parent in the MatDialog afterClosed subscription:</p><pre>@Component({<br>  template: &#39;&#39;<br>})<br>export class DialogEntryComponent {<br>  constructor(<br>    public dialog: MatDialog,<br>    <strong>private router: Router,<br>    private route: ActivatedRoute</strong><br>  ) {<br>    this.openDialog();<br>  }</pre><pre>  openDialog(): void {<br>    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {<br>      width: &#39;250px&#39;<br>    });</pre><pre>    dialogRef.afterClosed().subscribe(result =&gt; {<br>      <strong>this.router.navigate([&#39;../&#39;], { relativeTo: this.route });</strong><br>    });<br>  }<br>}</pre><p>Our app now correctly navigates to and from “/home/dialog”, but the data is not being passed as expected.</p><p>How do we pass the data? Our dummy component doesn’t have direct access to the inputted data. As discussed in our introduction, the direct access to inputted data to pass along to the dialog is a benefit of option 1. We can instead pass data using a service (NgRx, local storage, etc). For this example, we’ll create a dummy service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;</pre><pre>@Injectable()<br>export class DataService {<br>  animal: string;<br>  name: string;<br>}</pre><p>We’ll need to add the DataService to the providers array in main.ts.</p><p>Inject the DataService in the parent component:</p><pre>export class DialogOverviewExample {<br>  <strong>constructor(public dataService: DataService) { }</strong><br>}</pre><p>Update the parent component template to use the DataService:</p><pre>&lt;ol&gt;<br>  &lt;li&gt;<br>    &lt;mat-form-field&gt;<br>      &lt;input matInput [(ngModel)]=&quot;<strong>dataService.name</strong>&quot; placeholder=&quot;What&#39;s your name?&quot;&gt;<br>    &lt;/mat-form-field&gt;<br>  &lt;/li&gt;<br>  ...<br>  &lt;li *ngIf=&quot;<strong>dataService.animal</strong>&quot;&gt;<br>    You chose: &lt;i&gt;{{<strong>dataService.animal</strong>}}&lt;/i&gt;<br>  &lt;/li&gt;<br>&lt;/ol&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>Inject the DataService in the child dialog component. We’ll pass back data to the parent component using the service instead of the MatDialog afterClosed result parameter:</p><pre>export class DialogOverviewExampleDialog {<br>  <strong>animal: string;<br>  name: string;<br> </strong> <br>  constructor(<br>    public dialogRef: MatDialogRef&lt;DialogOverviewExampleDialog&gt;,<br>    <strong>private</strong> <strong>dataService: DataService</strong><br>  ) {<br>      <strong>this.animal = dataService.animal;<br>      this.name = dataService.name;</strong><br>  }<br>  <br>  onNoClick(): void {<br>    this.dialogRef.close();<br>  }<br>}</pre><p>Update the child dialog template to use the animal and name properties:</p><pre>&lt;h1 mat-dialog-title&gt;Hi {{<strong>name</strong>}}&lt;/h1&gt;<br>&lt;div mat-dialog-content&gt;<br>  &lt;p&gt;What&#39;s your favorite animal?&lt;/p&gt;<br>  &lt;mat-form-field&gt;<br>    &lt;input matInput [(ngModel)]=&quot;<strong>animal</strong>&quot;&gt;<br>  &lt;/mat-form-field&gt;<br>&lt;/div&gt;<br>...</pre><p>We want to pass data back to the parent if the user clicks the “Ok” button and clear the data if user clicks the “No Thanks” button. Update the child dialog template to handle the click instead of passing the animal back using the mat-dialog-close directive:</p><pre>...<br>&lt;div mat-dialog-actions&gt;<br>  &lt;button mat-button (click)=&quot;onNoClick()&quot;&gt;No Thanks&lt;/button&gt;<br>  &lt;button mat-button <strong>(click)=&quot;onOkClick()&quot;</strong> cdkFocusInitial&gt;Ok&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Update the DataService animal property from the child dialog component when the user clicks the “Ok” button, clear the DataService animal property when the user clicks the “No Thanks” button:</p><pre>export class DialogOverviewExampleDialog {<br>  ...<br>  onNoClick(): void {<br>    <strong>this.dataService.animal = undefined;</strong><br>    this.dialogRef.close();<br>  }</pre><pre><strong>  onOkClick(): void {<br>    this.dataService.animal = this.animal;<br>    this.dialogRef.close();<br>  }</strong><br>}</pre><h4>Done!</h4><p>This option favors applications that maintain state globally and have dialogs that need to exist at multiple route locations (a store checkout dialog at /camera/checkout, /accessories/checkout, etc). After creating a generic DialogEntryComponent, we only need to add the ‘checkout’ child route in the Router Module configuration and add a router-outlet to the parent’s template.</p><p>Here’s the final product:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-route-dialog-path%3Fembed%3D1%26file%3Dapp%252Fdialog-overview-example.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmaterial-dialog-route-dialog-path%3Ffile%3Dapp%252Fdialog-overview-example.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/23e441d1f03aa64a4d689f95ef4830da/href">https://medium.com/media/23e441d1f03aa64a4d689f95ef4830da/href</a></iframe><p>Follow me on Twitter :) <a href="https://twitter.com/john_crowson">@john_crowson</a></p><p>For more Angular goodness, be sure to check out the latest episode of <a href="https://www.spreaker.com/show/angular-show">The Angular Show podcast</a>.</p><h3>EnterpriseNG is coming November 4th &amp; 5th, 2021.</h3><p>Come hear top community speakers, experts, leaders, and the Angular team present for 2 stacked days on everything you need to make the most of Angular in your enterprise applications.<br>Topics will be focused on the following four areas:<br> • Monorepos<br> • Micro frontends<br> • Performance &amp; Scalability<br> • Maintainability &amp; Quality<br>Learn more here &gt;&gt; <a href="https://enterprise.ng-conf.org/">https://enterprise.ng-conf.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3fb7231c177" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ngconf/routing-to-angular-material-dialogs-c3fb7231c177">Routing to Angular Material Dialogs</a> was originally published in <a href="https://medium.com/ngconf">ngconf</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Angular Router Navigation Scroller]]></title>
            <link>https://medium.com/@jtcrowson/building-a-custom-angular-router-navigation-scroller-9f2bd6637baf?source=rss-671829e4d4a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f2bd6637baf</guid>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-router]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[John Crowson]]></dc:creator>
            <pubDate>Tue, 22 Jan 2019 14:11:00 GMT</pubDate>
            <atom:updated>2019-03-29T15:22:02.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Custom Navigation Scroller using Angular Router</h3><h3>Inspiration</h3><p>Angular Version 6.1 added the “Scroll Position Restoration” feature. It allows configuration of the scroll position on navigation.</p><p>`ScrollPositionRestoration` has been added to the option of the second argument of `RouterModule.forRoot` method, usually imported in the App Module. It includes three options with the following functionality:</p><blockquote>* ‘disabled’ — does nothing (default).</blockquote><blockquote>* ‘top’ — set the scroll position to 0,0..</blockquote><blockquote>* ‘enabled’ — set the scroll position to the stored position. This option will be the default in</blockquote><p>In my use case, the three “out of the box” solutions did not provide my desired solution. I want the same functionality as ‘enabled’, but do not want to change the scroll position when navigating away from a specified route (in my case, navigating away from a modal should persist the background scroll position).</p><p>Unfortunately, this code has almost non-existent documentation, leaving me to reverse engineer the functionality.</p><p><strong><em>Update (March 29, 2019): Angular has merged </em></strong><a href="https://github.com/angular/angular/commit/2b836c81a29485722ff44eb0df85bbdce228eed7"><strong><em>my pull request</em></strong></a><strong><em> to clarify the documentation. It’s scheduled to be released as a part of 7.2.x.</em></strong></p><h3>Reverse Engineering ScrollPositionRestoration</h3><p>My solution was to build my own custom Router Scroller functionality in my AppModule. But first, I had to learn how the ScrollPositionRestoration was implemented.</p><p>I started by checking out the <a href="https://github.com/angular/angular/pull/20030">original pull request</a>. Here’s what I learned:</p><ul><li>A new router event has been added, Scroll, which is always the last event emitted in a navigation lifecycle.</li><li>The Scroll event has three properties: routerEvent (a reference to the NavigationEnd event), position (tuple of numbers or null), and anchor (string or null, won’t cover in this post).</li></ul><p>Shockingly, at the time of this post (v7.2.1), none of the Scroll event properties are documented, although an <a href="https://github.com/angular/angular/issues/24547">issue has been raised</a> for this.</p><p>From reverse engineering the code, I learned that:</p><ul><li>On forward navigation, the position property is null.</li><li>On backward navigation, the position property contains the previous scroll position.</li></ul><p>With this in mind, I started by reimplementing the existing ‘enabled’ functionality:</p><pre>export class AppModule {<br>  constructor(router: Router, viewportScroller: ViewportScroller) {<br>    AppModule.scrollToTopOnForwardNavigation(router, viewportScroller);<br>  }</pre><pre>  static scrollToTopOnForwardNavigation(router: Router, viewportScroller: ViewportScroller): void {</pre><pre>    // Only scroll events, which emit when the navigation <br>    const scrollEvents$ = router.events.pipe(<br>      filter(event =&gt; event instanceof Scroll),<br>      map(event =&gt; event as Scroll)<br>    );</pre><pre>    scrollEvents$.subscribe(scrollEvent =&gt; {<br>      if (scrollEvent.position) {<br>        // backward navigation<br>        viewportScroller.scrollToPosition(scrollEvent.position);<br>      } else if (scrollEvent.anchor) {<br>        // anchor navigation<br>        viewportScroller.scrollToAnchor(scrollEvent.anchor);<br>      } else {<br>        // forward navigation<br>        viewportScroller.scrollToPosition([0, 0]);<br>      }<br>    });<br>  }<br>}</pre><h3>My Solution</h3><p>With the information I gained from reverse engineering, it was relatively simple to add my exception to not change the scroll position when navigating away from a modal:</p><pre>export class AppModule {<br>  constructor(router: Router, viewportScroller: ViewportScroller) {<br>    AppModule.scrollToTopOnNonModalNavigation(router, viewportScroller);<br>  }</pre><pre>static scrollToTopOnNonModalNavigation(router: Router, viewportScroller: ViewportScroller): void {</pre><pre>const scrollEvents$ = router.events.pipe(<br>      filter(event =&gt; event instanceof Scroll),<br>      map(event =&gt; event as Scroll)<br>    );</pre><pre>// Emits the previous URL after the router navigates to a new URL<br>const originUrl$ = router.events.pipe(<br>      filter(event =&gt; event instanceof NavigationEnd),<br>      map(event =&gt; event as NavigationEnd),<br>      pairwise(),<br>      map(navigationEvents =&gt; navigationEvents[0].url)<br>    );</pre><pre>scrollEvents$.pipe(<br>      withLatestFrom(originUrl$)<br>    ).subscribe(([scrollEvent, originUrl]) =&gt; {<br>      if (scrollEvent.position) {<br>        // backward navigation<br>        viewportScroller.scrollToPosition(scrollEvent.position);<br>      } else if (scrollEvent.anchor) {<br>        // anchor navigation<br>        viewportScroller.scrollToAnchor(scrollEvent.anchor);<br>      } else if (!originUrl.includes(&#39;/modal/&#39;)) {<br>        // forward navigation from non-modal route<br>        viewportScroller.scrollToPosition([0, 0]);<br>      }<br>    });<br>  }<br>}</pre><p>The only change to the scrollEvent subscription was changing the <strong>else</strong> to an <strong>else if</strong> to prevent scrolling if the navigation origin URL was a modal.</p><p>Please reach out to me on <a href="https://twitter.com/john_crowson">Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f2bd6637baf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>