<?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[Motf Creations - Medium]]></title>
        <description><![CDATA[A social and creative space for creatives. - Medium]]></description>
        <link>https://medium.com/motf-creations?source=rss----d07dbe5caa4c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Motf Creations - Medium</title>
            <link>https://medium.com/motf-creations?source=rss----d07dbe5caa4c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:15:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/motf-creations" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is the .NPMRC file for?]]></title>
            <link>https://medium.com/motf-creations/what-is-the-npmrc-file-for-d19fe6d69c9a?source=rss----d07dbe5caa4c---4</link>
            <guid isPermaLink="false">https://medium.com/p/d19fe6d69c9a</guid>
            <category><![CDATA[npm-scripts]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[command-line]]></category>
            <dc:creator><![CDATA[Thabo]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 17:14:53 GMT</pubDate>
            <atom:updated>2023-04-27T17:14:57.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is the .NPMRC file for?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96E2s24g-RetVDccuK3ENA.png" /></figure><blockquote>A quick look into what this file is used for in a NPM project.</blockquote><blockquote>As you might know already, NPM is a powerful package manager for Node/JS applications. If you do not know what Node/JS/NPM is, check out these links <a href="https://nodejs.org/en/about/"><em>NodeJS</em></a><em>, </em><a href="https://www.npmjs.com/"><em>NPM</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript"><em>JavaScript</em></a></blockquote><blockquote>In this article, I assume you have knowledge of Node/JS/NPM, and that you know how to use it, and you have an idea of what an <a href="https://en.wikipedia.org/wiki/INI_file"><strong><em>INI file forma</em></strong></a>t is and what it entails.</blockquote><h3>What is the .npmrc file?</h3><p>This file is a configuration file for NPM, it defines the <a href="https://docs.npmjs.com/misc/config">settings </a>on how NPM should behave when running commands.</p><p>What does the <strong>rc </strong>mean on configuration files, like for example <strong>.</strong><a href="https://bower.io/docs/config/"><strong>bowerrc</strong></a>?</p><p>The <strong>rc, </strong>taking from a <a href="https://stackoverflow.com/questions/11030552/what-does-rc-mean-in-dot-files"><strong>SO post</strong></a>, can stand for various things, but I will take that in this context, it stands for <strong>Runtime configuration.</strong></p><h4>There are several ways to configure NPM. You can do it via:</h4><ul><li>The command line by passing a setting with the NPM command you want to run.</li><li>Through ENV variables</li><li>And through..guess what.. <a href="https://docs.npmjs.com/files/npmrc"><strong>npmrc</strong></a></li></ul><p>I will only focus on one example on how you would set a specific flag/setting depending on the context of the command execution, that will be the <strong>loglevel </strong>flag<strong>.</strong></p><p>If you are working with NPM scripts, you might have noticed that when running a script there is some text echoed before the results of the underlying script, for example, check the execution of a JS script that adds two numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*frtxPPhqUp1gqmojU4O04A.png" /><figcaption>NPM script run</figcaption></figure><p>Notice that text? Something about the project details and script name, but anyway.</p><p>To configure NPM not to show this text when running scripts you can instead pass the <strong>loglevel </strong>flag along with the script’s execution, like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*NSeuxNASPNtRZUnY5o8SUA.png" /><figcaption>run silent</figcaption></figure><p>See how the text is now suppressed, yeah that is setting NPM via the command line, so the <strong>-silent </strong>flag is a value for the <strong>loglevel </strong>setting.</p><h4>How would you do that via the .npmrc file?</h4><p>In the root of your project, create a <strong>.npmrc </strong>and set the loglevel setting value like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*bqKZZV1EaXMrgAIQhukrog.png" /><figcaption>npmrc file</figcaption></figure><p>And that is it! now you do not have to supply the <strong>-silent</strong> flag when running your script.</p><pre>npm run hello-js</pre><h4>To set via the ENV variables I did the following:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*8-a3hozgyYSy9E216si_ow.png" /><figcaption>env var</figcaption></figure><p>I am not certain that this works, I did not reboot my system, it did not work when testing as I am guessing a system reboot is required for the ENV var to take effect.</p><p>Please comment on this if you’ve managed to get the ENV var working.</p><p>Cheers ✌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d19fe6d69c9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motf-creations/what-is-the-npmrc-file-for-d19fe6d69c9a">What is the .NPMRC file for?</a> was originally published in <a href="https://medium.com/motf-creations">Motf Creations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nx workspace: npm ERR! The Cypress App could not be downloaded.]]></title>
            <link>https://medium.com/motf-creations/nx-workspace-npm-err-the-cypress-app-could-not-be-downloaded-bd33c5cac1b?source=rss----d07dbe5caa4c---4</link>
            <guid isPermaLink="false">https://medium.com/p/bd33c5cac1b</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Thabo]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 09:42:19 GMT</pubDate>
            <atom:updated>2022-09-24T08:06:00.858Z</atom:updated>
            <content:encoded><![CDATA[<p>This error comes up when creating a new Angular workspace using the create-nx-workspace command.</p><p>I was connected to an organization’s network, when I ran the command below:</p><pre>npx create-nx-workspace@latest</pre><p>This resulted in the error below</p><p>&gt; NX Nx failed to create a workspace.</p><p>And the error log was something like below</p><pre>npm ERR! Installing Cypress (version: 10.8.0)</pre><pre>npm ERR!</pre><pre>npm ERR! [STARTED] Task without title.</pre><pre>npm ERR! The Cypress App could not be downloaded.</pre><pre>npm ERR!</pre><pre>npm ERR! Does your workplace require a proxy to be used to access the Internet? If so, you must configure the HTTP_PROXY environment variable before downloading Cypress. Read more: https://on.cypress.io/proxy-configuration</pre><pre>npm ERR!</pre><pre>npm ERR! Otherwise, please check network connectivity and try again:</pre><pre>npm ERR!</pre><pre>npm ERR! ----------</pre><pre>npm ERR!</pre><pre>npm ERR! URL: https://download.cypress.io/desktop/10.8.0?platform=win32&amp;arch=x64</pre><pre>npm ERR! <strong>Error</strong>: self signed certificate in certificate chain</pre><pre>npm ERR!</pre><pre>npm ERR! ----------</pre><pre>npm ERR!</pre><pre>npm ERR! Platform: win32-x64 (10.0.19044)</pre><pre>npm ERR! Cypress Version: 10.8.0</pre><p>Something about <a href="https://docs.cypress.io/guides/references/proxy-configuration.html#Proxy-environment-variables">proxy configuration</a> for Cypress.</p><p>I did not know the organization’s proxy server so I could not do the configuration for Cypress.</p><p>I found a solution on <a href="https://stackoverflow.com/questions/60379393/cypress-installation-fails-with-proxy-setup">Stackoverflow</a>.</p><h3>Solution</h3><ol><li>Used the URI from the error log to download Cypress<br>npm ERR! URL: <a href="https://download.cypress.io/desktop/10.8.0?platform=win32&amp;arch=x64">https://download.cypress.io/desktop/10.8.0?platform=win32&amp;arch=x64</a></li><li>Set the Cypress binary variable to point to this installation. Note that I was in the workspace’s working directory when I ran the below command.<br>CYPRESS_INSTALL_BINARY=~/Downloads/cypress.zip npm install cypress — save-dev</li></ol><p>This installed Cypress together with the missing dependencies that were missing for the workspace’s creation.</p><p>This resolved my specific issue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd33c5cac1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motf-creations/nx-workspace-npm-err-the-cypress-app-could-not-be-downloaded-bd33c5cac1b">Nx workspace: npm ERR! The Cypress App could not be downloaded.</a> was originally published in <a href="https://medium.com/motf-creations">Motf Creations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Universal: ReferenceError: window is not defined]]></title>
            <link>https://medium.com/motf-creations/angular-universal-referenceerror-window-is-not-defined-f0ed140e3210?source=rss----d07dbe5caa4c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f0ed140e3210</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[angular-universal]]></category>
            <dc:creator><![CDATA[Thabo]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 08:57:56 GMT</pubDate>
            <atom:updated>2021-02-19T10:13:50.757Z</atom:updated>
            <content:encoded><![CDATA[<p>This error can be caused by a reference to the Window object if you are rendering your application from a server like Node.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbRRHna0oR5RlCzoeAjLlg.png" /><figcaption>Image source: <a href="https://learnwithmanoj.com/angular-5-universal/">https://learnwithmanoj.com/angular-5-universal/</a></figcaption></figure><p>I will share how I have solved this issue, in my case this was caused by <a href="https://www.npmjs.com/package/hammerjs">HammerJS</a> which does not support server-rendered applications. This error can also be caused by your code that references the Window object or any third-party module that references the Window object without having a defensive check against an undefined value of Window.</p><p>Angular core: v10.0.5</p><p>I have incurred many errors when resolving this issue, during the processes, I will quickly list some of the issues a had and tentative solutions to them.</p><ul><li><strong>No such file or directory, google/firestore/v1/firestore.proto’ <br>Solutions: </strong>In angular.json file, I have added the following:</li></ul><pre>...<br>&quot;server&quot;: {<br>  &quot;builder&quot;: &quot;@angular-devkit/build-angular:server&quot;,<br>   &quot;options&quot;: {<br>     &quot;outputPath&quot;: &quot;dist/PROJECT_NAME/server&quot;,<br>     &quot;main&quot;: &quot;server.ts&quot;,<br>     &quot;tsConfig&quot;: &quot;tsconfig.server.json&quot;,<br>     &quot;stylePreprocessorOptions&quot;: {<br>       &quot;includePaths&quot;: [&quot;src/assets/styles&quot;]<br>      },<br>     &quot;externalDependencies&quot;: [&quot;@firebase/firestore&quot;]<br>   }<br>}<br>...</pre><p>The <strong>externalDependencies </strong>option allows you to exclude the listed dependencies in the array from the main bundle and instead, the generated bundle relies on these dependencies to be available during runtime.<br>I understand the above statement but do not understand why I got the error for <em>@firebase/firestore.</em></p><p>Some suggestions were to exclude the following packages by listing them under <strong>externalDependencies.<br></strong> &quot;grpc&quot;,<br> &quot;@grpc/proto-loader&quot;</p><h4>But what is gRPC?</h4><blockquote>gRPC is an open source remote procedure call system initially developed at Google in 2015.</blockquote><blockquote>In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.<br>By default, gRPC uses<strong> </strong><a href="https://developers.google.com/protocol-buffers/docs/overview"><strong>Protocol Buffers</strong></a><br>SOURCE: <a href="https://grpc.io/docs/what-is-grpc/introduction/">https://grpc.io/docs/what-is-grpc/introduction/</a></blockquote><h4><strong>What are Protocol Buffers?</strong></h4><blockquote>Protocol buffers are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data — think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.<br>SOURCE: <a href="https://developers.google.com/protocol-buffers">https://developers.google.com/protocol-buffers</a></blockquote><h4>And what&#39;s the thing with gRPC and Firebase/Firestore?</h4><p>I do not know, I am only guessing that the relationship between the two involves the mechanics of the Google cloud services like the Firebase cloud functions, the Database rules .etc.</p><h3>Handle the Window object in my Angular code</h3><p>First I have the service that wraps the global Window object.</p><pre>import { Injectable } from &#39;@angular/core&#39;;</pre><pre>function _window(): any {<br>  return window;<br>}</pre><pre>@Injectable()<br>export class WindowRef {<br> get nativeWindow(): any {<br>   return _window();<br> }<br>}</pre><p>I have provided this to the app’s main module <strong>AppModule</strong> so that it is in the upper-most injector so that it is available in the whole application.</p><p>I have used this service by injecting it in the components that use the Window object like below, I have omitted some code for brevity.</p><pre>import { PLATFORM_ID } from &quot;@angular/core&quot;;</pre><pre>import { isPlatformBrowser } from &#39;@angular/common&#39;;<br>import { WindowRef } from &#39;./services/windowRef.service&#39;;</pre><pre>...</pre><pre>constructor(<br> @Inject(PLATFORM_ID) private platformId: any,<br> private windowRef: WindowRef<br>){}</pre><pre>...</pre><pre>if(isPlatformBrowser(this.platformId)) {</pre><pre>  // Use the window reference: this.windowRef</pre><pre> Eg: this.windowRef.nativeWindow.location.pathname</pre><pre>}</pre><p>Let’s go through the important parts for the above code:</p><p><strong>PLATFORM_ID </strong>is an Opaque Token (Now <a href="https://angular.io/api/core/InjectionToken">InjectionToken</a>) of type String object, this token helps the DI to get the current platform (browser/server).<br><strong>isPlatformBrowser </strong>a common function that returns whether a platform id represents a browser platform.</p><p>Cool.. with the above code snippet, you can generalize the defensive mechanism for the existence of the Window object as you like, if you are abusing the window Object in your application, just make sure you do the check if it is a browser or server. There is a function to check if the platform is a server — <a href="https://angular.io/api/common/isPlatformServer"><strong>isPlatformServer</strong></a> .</p><h3>Fixing Window issue for HammerJS</h3><p>This fix was straight forward, I have quickly gone through the docs of HammerJS and noticed that the check if the Window exists is not there and the usage of Window happens in the exported module, which caused the Window to be undefined in my SSR even when I used <strong>isPlatformBrowser </strong>before I can use HammerJS.</p><p>NOTE: Using <strong>isPlatformBrowser </strong>against HammerJS did not work because the error happened on the import level/line of HammerJS.</p><h4>Solution</h4><p>Use <a href="https://www.npmjs.com/package/@egjs/hammerjs">@egjs/hammerjs</a>, this version of HammerJS is server friendly and is tree-shakable. So I have installed this module and did not have to change anything because it uses the same interface as the old HammerJS and also comes with the type definitions;</p><p>So go ahead and import this new module and remove the old import;</p><h3>Fix ReferenceError: getComputedStyle is not defined for GSAP</h3><p>I am using a nice great animation engine in my application; But for SSR, I got the above error.</p><h4>Solution</h4><p>Use <a href="https://www.npmjs.com/package/domino"><strong>domino</strong></a><strong> </strong>a server-side DOM implementation based on Mozilla’s dom.js.</p><p>With domino, I am not sure why it solved my issue with getComputedStyle (A Window global) being undefined but not my other issues with Window being undefined. So I am just going to drop the code that a have on my server.ts file to address issues with browser/server globals.<br>The below code is at the top of the server.ts file</p><pre>(global as any).WebSocket = require(&#39;ws&#39;);<br>(global as any).XMLHttpRequest = require(&#39;xhr2&#39;);</pre><pre>const domino = require(&#39;domino&#39;);<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);</pre><pre>...</pre><pre>const distFolder = join(process.cwd(), &#39;dist/motif/browser&#39;);<br>const template = fs.readFileSync(path.join(distFolder, &#39;index.html&#39;)).toString();</pre><pre>const win = domino.createWindow(template.toString());<br>global[&#39;window&#39;] = win;<br>global[&#39;document&#39;] = win.document;<br>global[&#39;self&#39;] = win<br>global[&#39;IDBIndex&#39;] = win.IDBIndex<br>global[&#39;document&#39;] = win.document<br>global[&#39;navigator&#39;] = win.navigator<br>global[&#39;getComputedStyle&#39;] = win.getComputedStyle;</pre><pre>...</pre><pre>import &#39;zone.js/dist/zone-node&#39;;<br>import { AppServerModule } from &#39;./src/main.server&#39;;</pre><p>Note the import of <strong>AppServerModule </strong>after my play there, there seems to be importance with the order of imports, so note that.</p><p>The SSR scripts in the package.json</p><pre>&quot;dev:ssr&quot;: &quot;ng run motif:serve-ssr&quot;,<br>&quot;serve:ssr&quot;: &quot;node dist/motif/server/main.js&quot;,<br>&quot;build:ssr&quot;: &quot;ng build --prod &amp;&amp; ng run motif:server:production&quot;,<br>&quot;prerender&quot;: &quot;ng run motif:prerender&quot;</pre><p>After all the hassle, when running the below script, the build completes with a few warnings inherent to my project.</p><pre>npm run build:ssr &amp;&amp; npm run serve:ssr</pre><p>By the way, all the Angular Universal boiler plating was achieved with the below command</p><pre>ng add @nguniversal/express-engine</pre><p>Refer to <a href="https://angular.io/guide/universal">Angular Universal</a>.</p><p>And that’s it! if I have missed something I will update this article. Ciao</p><p>UPDATE:</p><p>The <strong>isPlatformBrowser</strong> offered by Angular seems to be not helping out with the window Object availability checks.</p><p>There is an open issue regarding this on <a href="https://github.com/angular/universal/issues/1675/">Github</a>.</p><p>Hopefully, this will be resolved by the Angular team because having to change the source of third party libraries that uses the Window object without a check is just a pain on the fingers.</p><p>I will keep this writing in sync.</p><p><strong>UPDATE:</strong> I have solved my issue a while back and forgot to update this article.</p><p>If you are having this issue and the above solutions did not help.</p><p>Please see this <a href="https://github.com/angular/universal/issues/1675#issuecomment-667364585">Github thread</a> for some more solutions which one of them was the one I have posted that solved the issue in my case. I hope this gives more hope.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ed140e3210" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motf-creations/angular-universal-referenceerror-window-is-not-defined-f0ed140e3210">Angular Universal: ReferenceError: window is not defined</a> was originally published in <a href="https://medium.com/motf-creations">Motf Creations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the difference between disabling a form control through reactive forms API and HTML…]]></title>
            <link>https://medium.com/motf-creations/exploring-the-difference-between-disabling-a-form-control-through-reactive-forms-api-and-html-477aebcadc30?source=rss----d07dbe5caa4c---4</link>
            <guid isPermaLink="false">https://medium.com/p/477aebcadc30</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Thabo]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 13:13:51 GMT</pubDate>
            <atom:updated>2021-10-09T00:51:39.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the difference between disabling a form control through reactive forms API and HTML attributes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*No0aOCAGY8RpbaFv1WTG5A.png" /></figure><p>Having parts of a form disabled is a common requirement for any large application. Sometimes users must be prevented from interacting with a form based on their role in an application; an input field can also be disabled because its value is pre-populated and no user input is required.</p><p>In this article, we will explore different ways to disable reactive form controls and see how they affect the form’s state (which in turn would affect our application state)</p><p>Below is a simple form with two fields and a button. We will use this setup to illustrate the different ways to disable form controls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*AiF-17lQzOH8uSfL" /></figure><p>Here’s how we create this form in our application’s code:</p><h3>Form component class</h3><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnInit {<br>  form: FormGroup;<br><br>  constructor(private formBuilder: FormBuilder) { }<br><br>  ngOnInit(): void {<br>    this.form = this.formBuilder.group({<br>      firstName: [{ value: &#39;Foo&#39;, disabled: true }, [Validators.required]],<br>      lastName: [&#39;Bar&#39;]<br>    });<br>  }<br><br>  onSubmit(): void { }<br><br>  get firstName(): FormControl {<br>    return this.form.controls.firstName as FormControl;<br>  }<br><br>  get lastName(): FormControl {<br>    return this.form.controls.lastName as FormControl;<br>  }<br>}</pre><p>Note that in the component class I have defined accessors to the two form controls for the ease of access.</p><h3>Form template</h3><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br> &lt;h1&gt;Angular Reactive Form&lt;/h1&gt;<br> &lt;input formControlName=&quot;firstName&quot; placeholder=&quot;First Name&quot; /&gt;<br> &lt;input formControlName=&quot;lastName&quot; placeholder=&quot;Last Name&quot; /&gt;<br> &lt;button (click)=&quot;onSubmit()&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>I’m using formGroup and formControlName directives from Reactive Forms API here.</p><h3>Using the FormControl’s disable() instance method</h3><p>This method will disable both the UI control and the FormControl’s instance. Let us see how we’d use this method to disable a form control. In the <strong>ngOnInit</strong> function, after creating the form instance, we can disable the lastName form control like below.</p><pre>ngOnInit(): void {<br>    this.form = this.formBuilder.group({<br>      firstName: [{ value: &#39;Foo&#39;, disabled: true },  [Validators.required]],<br>      lastName: [&#39;Bar&#39;]<br>    });<br><br>    this.lastName.disable();<br>  }</pre><p>If we <em>console.log</em> the control <strong>lastName</strong> we’ll see its instance will be disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*saXml9f0c7STRDFr" /><figcaption>Showing the affected properties for a disabled form control</figcaption></figure><p>This way is quick and straightforward.</p><h3>When would this way of disabling FormControls be a disadvantage?</h3><p>When we depend on a FormGroup’s validity status to make some decisions. Let’s see how, let’s change our ngOnInit code a bit by adding console logs.</p><pre>ngOnInit(): void {<br>    this.form = this.formBuilder.group({<br>      firstName: [{ value: &#39;Foo&#39;, disabled: true }, [Validators.required]],<br>      lastName: [&#39;Bar&#39;]<br>    });<br><br>    this.lastName.disable();<br><br>    console.log(this.lastName);<br>    console.log(&#39;Form:::&#39;, this.form);<br>  }</pre><p>We’ve given the form controls default values, disabled both the controls and required the <strong>firstName</strong> control by having a required validator on its configuration. Note that the <strong>firstName</strong> control is disabled by default.</p><p>The last <em>console.log</em>’s output is below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*E5tqlVC_ofEvCeJw.png" /><figcaption>Showing how having all controls disabled in a form group affects the forms status and validity</figcaption></figure><p>Something worth noting is that when we have all form controls disabled, irrespective of their validity status’, the controls’ instance <strong>status</strong> properties will be set to “DISABLED” hence the FormGroup’s status will also be set to “DISABLED”.</p><p>In the log snippet above, can you also see that the form’s <strong>valid</strong> and <strong>invalid</strong> properties are both <strong>false</strong>, but the controls have values and are valid? Can you see the confusion this way of disabling controls might cause when the form’s validity is a dependency in some decisions we have to make?</p><p>For example, let’s say we have a big form implementation and we are aware that some form fields will need to be disabled.</p><p>For instance, say we have a second form in a separate page that requires the firstName and lastName the user had entered in the first form. We would, in the second form, disable and pre-populate the firstName and lastName inputs; now let’s say we want to propagate the form’s value to some state store when the form value or status changes but when the form is <strong>valid</strong>.</p><p>Let’s consider a case where we have a listener to the form value changes and we have some controls whose values are changed by an external source.</p><pre>this.form.valueChanges<br>     .pipe(<br>       distinctUntilChanged()<br>     )<br>     .subscribe(<br>       (status) =&gt; {<br>         if (this.form.status === &#39;VALID&#39;) {// `this.form.status` is &quot;DISABLED&quot;<br>           // set some state value<br>         }<br>       }<br>     );<br> <br>   this.lastName.setValue(&#39;Baz&#39;);</pre><p>We set an observer to the form’s value changes and after we change the value of the lastName control.</p><p>Our form’s value will not sync with our application state store because when the observer executes, it will find that the form’s status is <strong>DISABLED</strong> even though the form value is valid which might cause confusion and discrepancies in our code especially when the state store has observers to it also.</p><p>That could be an issue with this mechanism of disabling form controls.</p><p>Another way to disable form controls is the one we use to disable the <strong>firstName</strong> control when instantiating the form itself.</p><pre>this.form = this.formBuilder.group({<br>      firstName: [{ value: &#39;Foo&#39;, disabled: true }, [Validators.required]],<br>      lastName: [&#39;Bar&#39;]<br>    });</pre><p>This has the same effect described above when a control is disabled using the .disable() control method.</p><h3>Using a template attribute to disable FormControls</h3><p>Yet another way is to add disabled=true attribute to HTML in the template like this:</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br> &lt;h1&gt;Angular Reactive Form&lt;/h1&gt;<br> &lt;input formControlName=&quot;firstName&quot; placeholder=&quot;First Name&quot;&gt;<br> &lt;input formControlName=&quot;lastName&quot; disabled=&quot;true&quot; placeholder=&quot;Last Name&quot;&gt;<br> &lt;button (click)=&quot;onSubmit()&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>Which gives the below warning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*VRytBG9a2ShFTNZU" /></figure><p>This warning is thrown to warn you about the potential errors regarding <strong>“changed after checked”</strong> that might be thrown in result of using the disabled attribute directive with a reactive form.</p><p>What this means is that, if the disabled attribute would expect a dynamic expression like [disabled]=&quot;isDisabled&quot; (resulting in <strong>true</strong> or <strong>false</strong>, not just a <strong>static</strong> true for example) resulting in a <strong>binding</strong> eligible for being checked during change detection, it would make the binding susceptible to the <strong>&quot;changed after checked&quot;</strong> error, that is, the expression could be false when change detection is run and then true when the change detection verification phase runs.</p><p>A deep dive into the ‘ExpressionChangedAfterItHasBeenCheckedError’ error can be found <a href="https://indepth.dev/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error">here</a> .</p><p>So to avoid the warning, you can use the [attr.*] binding like this:</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br> &lt;h1&gt;Angular Reactive Form&lt;/h1&gt;<br> &lt;input formControlName=&quot;firstName&quot; placeholder=&quot;First Name&quot;&gt;<br> &lt;input formControlName=&quot;lastName&quot; [attr.disabled]=&quot;true&quot; placeholder=&quot;Last Name&quot;&gt;<br> &lt;button (click)=&quot;onSubmit()&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>There’s no warning, but it is worth noting that this will add the HTML disabled attribute which cannot be toggled using just true and false (as false also results in a disabled field), null and undefined can be used to enable the field. Another way to enable a field with this attribute with value set to true, false or any truthy value is by removing it from the field.</p><p>Both approaches have the same outcome, a form with a status of <strong>VALID</strong>, which is what we want to offset the limitation that comes with using the first approach described above (<strong>Using the FormControl’s disable() instance method</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*Qw5mdPmOpPlZ6te8.png" /><figcaption>The form’s value is missing the firstNames’ property and value</figcaption></figure><p>However, it is important to note the form’s value does not have the <strong>firstName’s</strong> control value because it is disabled, this happens when some of the form controls are disabled <strong>(Using the FormControl’s disable() instance method or from the form configuration like for the firstName control) </strong>and some are enabled or disabled using the <em>[disabled]</em> template directive.</p><p>To circumvent this issue, we can use a form’s instance method to get the raw form value that will include values of disabled controls on the form.</p><pre>this.form.getRawValue()</pre><pre>console.log(this.form.value);<br>console.log(this.form.getRawValue());<br><br>// The logs will have</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*4I7c90Ubfe-xXEvh.png" /><figcaption>The results of using a FormGroup’s .value and getRawValue properties</figcaption></figure><p>With the second approach <strong>(Using a template attribute to disable FormControls)</strong> we can expect what we see on the form UI to mirror the value of the form’s instance without affecting the controls instances.</p><p>Another way similar to the latter (<strong><em>[attr.disabled]</em></strong>) is to use the <strong>readonly</strong> attribute.</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br> &lt;h1&gt;Angular Reactive Form&lt;/h1&gt;<br> &lt;input formControlName=&quot;firstName&quot; placeholder=&quot;First Name&quot;&gt;<br> &lt;input formControlName=&quot;lastName&quot; readonly=&quot;true&quot; placeholder=&quot;Last Name&quot;&gt;<br> &lt;button (click)=&quot;onSubmit()&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>This one has the same effect as using the disabled attribute but does not apply disabled visuals to the control, this will disable the input control but to the eye it will look like the control is enabled.</p><p>You can simply style the input like below.</p><pre>input {<br>   margin-bottom: 8px;<br>   width: 250px;<br>   height: 45px;<br>   border-radius: 3px;<br>   padding-left: 10px;<br>   border: 1px solid rgba(0, 0, 0, 0.4);<br> <br>   &amp;:read-only {<br>     color: rgb(84, 84, 84);<br>     cursor: default;<br>     background-color: rgba(239, 239, 239, 0.3);<br> <br>     &amp;:focus {<br>       outline: none;<br>     }<br>   }<br> }</pre><p>Those are the differences I have experienced with the different ways of disabled form controls.</p><h3>In conclusion</h3><p>We have seen the different ways we can use to disable form control. They are the following:</p><ul><li>Using the FormControl’s disable() instance method</li><li>Disabling a FormControl from the form configuration</li><li>Using a template attribute to disable FormControls like <strong><em>disable</em></strong>, <strong><em>[attr.disable]</em></strong> and <strong><em>readonly</em></strong></li></ul><p>We have also seen how the first two approaches can affect the form’s status value (Which could possibly affect the application state if it is synced with the form’s state).<br>Depending on your requirements and use case, it is beneficial to consider beforehand the approach that will not limit your flexibility when working with reactive forms.</p><p>The Git repo for the demo project is <a href="https://admin.indepth.dev/ghost/#/editor/post/610ce85779dbc57df92a1260">here</a>.</p><p><a href="https://github.com/Teebo/explore-disable">GitHub - Teebo/explore-disable</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=477aebcadc30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motf-creations/exploring-the-difference-between-disabling-a-form-control-through-reactive-forms-api-and-html-477aebcadc30">Exploring the difference between disabling a form control through reactive forms API and HTML…</a> was originally published in <a href="https://medium.com/motf-creations">Motf Creations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrate from CSS to SCSS stylesheets for existing Angular application]]></title>
            <link>https://medium.com/motf-creations/migrate-from-css-to-scss-stylesheets-for-existing-angular-application-d61f8061f5b7?source=rss----d07dbe5caa4c---4</link>
            <guid isPermaLink="false">https://medium.com/p/d61f8061f5b7</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[scss]]></category>
            <dc:creator><![CDATA[Thabo]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 09:46:18 GMT</pubDate>
            <atom:updated>2021-10-08T13:12:39.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*ic7BnzH8YRYC6FDLQ8jetg.png" /></figure><h3>Migrate from CSS to SCSS stylesheets for an existing Angular application</h3><blockquote><em>A quick guide to using SCSS in an Angular application that was scaffolded to use the default stylesheet format.</em></blockquote><p>You might have forgotten to provide the <strong><em>style=scss </em></strong><em>flag</em> or maybe you didn’t know that it existed when you were generating a new Angular application using the Angular CLI, and now you want to switch to using the SCSS stylesheet format in your project, this transition can be daunting in cases where the project has already gotten big.</p><p>In this article, I will cover:</p><ul><li>Using an Angular schematics NPM package to perform the migration with just one command.</li><li>The manual way of performing the migration i.e. using the ng cli command.</li><li>Using the NPM package renamer to perform the migration</li></ul><p>I will not cover what <a href="https://sass-lang.com/">SCSS</a> and <a href="https://angular.io/guide/schematics">Angular Schematics</a> are in this article because I presume you know what these are. You can read on a great Angular Schematic series of articles on <a href="https://indepth.dev/angular-schematics-from-0-to-publishing-your-own-library-i/#default-debug-mode">inDepth.dev</a></p><p>Normally, to generate a new Angular project that uses SCSS stylesheets using the Angular CLI, you’d have to run the following command.</p><pre>ng new my-scss-app --style=scss</pre><p>A quick and easy way to perform the migration is to use the schematic NPM package <a href="https://www.npmjs.com/package/schematics-scss-migrate">schematics-scss-migrate</a>. Read more on what this schematic package does on <a href="https://www.npmjs.com/package/schematics-scss-migrate">NPM</a>.</p><p><a href="https://www.npmjs.com/package/schematics-scss-migrate">schematics-scss-migrate</a></p><h3>Using the NPM package <a href="https://www.npmjs.com/package/schematics-scss-migrate">schematics-scss-migrate</a>.</h3><p>To migrate your project using this package, all you have to do is to install the package, ideally as a <a href="https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file">dev-dependency</a> and run the command below under your project workspace dir.</p><p><em>NOTE: You can use </em><strong><em>— dry-run=true</em></strong><em> for testing before doing the actual migration.</em></p><pre>ng g schematics-scss-migrate:scss-migrate</pre><p>And that’s it, the above command did the following.</p><ul><li>Renamed all the stylesheets in the src folder recursively.</li><li>Altered the styleUrls value to point to the new file names for the stylesheet in the component classes relative to the component style files.</li><li>Updated the component styles schematics value in the angular.json file or creates one if the schematic does not exist.</li><li>And renamed styles.css references to .scss in the angular.json file</li></ul><h3>The manual migration method using the ng CLI</h3><p><em>NOTE: For Angular CLI versions older than v6 beta, use ng set in place of ng config.</em></p><p>With a change that came with Angular 9, <strong>styleext</strong> was renamed to <strong>style, </strong>if you are on version 9 or later, then your command should be</p><pre>ng config schematics.<a href="http://twitter.com/schematics/angular">@schematics/angular</a>:component.style scss</pre><p>Or you can directly set the schematics in the <strong><em>angular.json</em></strong><em> </em>config file like the below:</p><pre>&quot;schematics&quot;: {<br>    &quot;<a href="http://twitter.com/schematics/angular">@schematics/angular</a>:component&quot;: {<br>      &quot;style&quot;: &quot;scss&quot;<br>    }<br> ...<br>  }</pre><p>After that, in the <strong><em>angular.json</em></strong><em> </em>file, change the file extension of the <strong><em>style.css</em> </strong>for your project build and test options to <strong><em>style.scss, </em></strong>refer to the below.</p><pre>{<br> &quot;projects&quot;: {<br>     &quot;your-project-name&quot;: {<br>         ...<br>            &quot;architect&quot;: {<br>             &quot;build&quot;: {<br>                 &quot;options&quot;: {<br>                     &quot;styles&quot;: [<br>                           &quot;src/styles.css&quot; // update<br>                           ...<br>                        ]<br>                        ...<br>                    }<br>                    ...<br>                },<br>               &quot;test&quot;: {<br>                   ...<br>                     &quot;options&quot;: {<br>                   ...<br>                       &quot;styles&quot;: [<br>                         &quot;src/styles.css&quot; // update<br>                       ],<br>     }<br>     },<br>            }<br>        }<br>    }<br>}</pre><p>And then to rename the stylesheet files, follow the instructions below.</p><h3>Changing the project’s stylesheet files from .css to .scss file extensions using the renamer NPM package.</h3><p>To achieve this the most efficient way, I have used a NPM package: <a href="https://www.npmjs.com/package/renamer">renamer</a>.</p><p>I have installed the package globally (You can use npx if you want to)</p><pre>npm i -g renamer</pre><p>Now, in the terminal, navigate to the project’s src directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*c0xmfw4IPKeSTwzt.png" /></figure><p>Before you continue with running commands on your project, stage — commit your work and maybe switch to a new branch to play around with the renamer tool, you can read more on it <a href="https://www.npmjs.com/package/renamer">here</a>.</p><p>Let’s test the tool, <em>NOTE: Use the </em><strong><em>-d</em></strong><em> flag for a </em><strong><em>DRY-RUN</em></strong><em> of the command</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*EO0AwXMn07QS5MlU.png" /></figure><p>The above command renames all files with .<strong>CSS</strong> to .<strong>SCSS</strong> in the current working directory which is <strong>src </strong>since we had navigated to it, this is because of the wildcard/glob at the far end of the command which is <strong>“*”, </strong>now that we see that the command does what it should, go ahead and remove the -<strong>d</strong> flag from the command to apply the execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*VQNOM3REug4B4XEh.png" /></figure><p>The changes where successful</p><p>Before command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*Z4AKgxrG7quww91N.png" /></figure><p>After command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*QWt4a96ZUYzSyHV4.png" /></figure><p>Note that we have run the command twice on the styles.scss because of our testing in the beginning, now it is styles.scss, so correct that.</p><p>Now that we have achieved that, we have to change the source to use the new files extension, as a good Angular convention suggests that we name the stylesheets of our components by suffixing them with .<strong>component.css</strong> as our component files, it becomes easy to refactor the project as a whole at one go, for me it was at least, I had searched globally for any file with the .<strong>component.css </strong>reference using the shortcut <strong>Ctrl + Shift + f</strong> and replace all with <strong>Ctrl + Shift + h.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*i1GrmXUILWCgGMn4.png" /></figure><p>My project has many references so the shortcuts and following the Angular conventions saved me some time.</p><p>The project’s build is green, so yeah that is how you can quickly migrate from <strong>.css</strong> to <strong>.scss</strong> stylesheets for an existing Angular application<em>.</em></p><p>It is up to you which method you pick, but for me, the <em>schematic-scss-migrate</em> package seems to be the easiest approach and also considering that it is safe to use because you can use the dry-run option so you can verify the migration.</p><p>I hope you enjoyed reading it.</p><p>See the source of <strong><em>schematics-scss-migrate</em></strong> below:</p><p><a href="https://github.com/Teebo/scss-migrate">Teebo/scss-migrate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61f8061f5b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motf-creations/migrate-from-css-to-scss-stylesheets-for-existing-angular-application-d61f8061f5b7">Migrate from CSS to SCSS stylesheets for existing Angular application</a> was originally published in <a href="https://medium.com/motf-creations">Motf Creations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing reusable and reactive forms in Angular]]></title>
            <link>https://medium.com/motf-creations/implementing-reusable-and-reactive-forms-in-angular-fd42e60a8127?source=rss----d07dbe5caa4c---4</link>
            <guid isPermaLink="false">https://medium.com/p/fd42e60a8127</guid>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular-cli]]></category>
            <dc:creator><![CDATA[Thabo]]></dc:creator>
            <pubDate>Thu, 04 Feb 2021 07:45:09 GMT</pubDate>
            <atom:updated>2021-10-08T13:58:20.772Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will learn about two ways to implement reactive and reusable forms that have the capability to be used as sub-forms and also be used as standalone forms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*ze__D6snwoqisze0g7J1Ng.png" /></figure><p>I assume you know what forms are and you have worked with Angular <a href="https://angular.io/guide/reactive-forms">reactive forms</a>.</p><p>We will look at two approaches to achieve this:</p><ol><li>Using the<a href="https://angular.io/api/forms/ControlContainer"> ControlContainer</a> which enables us to pass a parent form down to it’s sub-forms which are implemented as components.</li><li>And the<a href="https://angular.io/api/core/ViewChild"> @ViewChild</a> which help us get a class instance of the component which in this case will be a form component instance.</li></ol><p>Angular provides two approaches to configure and implement forms, these are <em>reactive forms </em>and <em>template-driven, </em>in this article we will be referring to reactive forms.</p><h3>The forms UI Demo</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdKvm_Ie-020%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdKvm_Ie-020&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdKvm_Ie-020%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd3fb9734dc133f728ece294638120a/href">https://medium.com/media/dfd3fb9734dc133f728ece294638120a/href</a></iframe><p>As demonstrated on the above video, we have one big form with 2 sub-forms:</p><ul><li>HeroComponent (Parent)</li><li>PowersComponent (Sub-form queried using the @ViewChild decorator)</li><li>HobbiesComponent (Sub-form implemented using the ControlContainer class)</li></ul><h3>Implementing a sub-form using the @ViewChild decorator</h3><p>Let’s start off with the best approach that uses a decorator that enables the parent form (<strong>HeroComponent</strong>) to query the component class instance of our child/sub-form which is the <strong>PowersComponent, </strong>see code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440e32700198e77c01405540c01c4f3b/href">https://medium.com/media/440e32700198e77c01405540c01c4f3b/href</a></iframe><p>As you can see in the <em>HeroComponent’s </em>template that the PowersComponent needs no further inputs</p><pre>&lt;nb-card&gt;<br>  &lt;nb-card-header&gt;Super Power&lt;/nb-card-header&gt;<br>  &lt;nb-card-body class=&quot;col&quot;&gt;<br>    &lt;app-powers&gt;&lt;/app-powers&gt; // here<br>  &lt;/nb-card-body&gt;<br>&lt;/nb-card&gt;</pre><p>But if you can check the <em>HeroComponent</em> class, you will notice how we get the instance of the Powers sub-form component class and calling the <strong><em>createFormGroup</em></strong> public member function to return us the <em>PowersComponent</em> <em>FormGroup</em> configuration instance.</p><pre>@ViewChild(PowersComponent, { static: true }) public powersComponent: PowersComponent;</pre><p>Note how the <strong><em>@ViewChild</em></strong> options uses the<strong> <em>static: true </em></strong>to resolve the component instance as soon as possible so that we have the sub-form instance of the <em>PowersComponent</em> class.</p><p>And check line 21 of the <em>HeroComponent.ts</em> file that creates the <em>PowersComponent</em> form.</p><pre>powers: this.powersComponent.createFormGroup(),</pre><p>That is it on how to create a reusable and reactive sub-form using the <em>@ViewChild decorator</em>, which I’m inclined to because I find it straightforward to implement and easier to maintain as the sub-form and the parent form are decoupled from one another and provides the below benefits:</p><ul><li>The parent form needs not to know about the sub-form’s instance at all. All it needs is, for the sub-form component class to have a <strong><em>createFormGroup</em></strong> public member function that returns a FormGroup’s instance.</li><li>A change on the sub-form’s form configuration does not affect the parent form’s configuration or its template in any way.</li></ul><p>Cool, so what about setting up the unit test for such a setup?</p><p>Easy-peasy, check the code below</p><h3>Unit test for @ViewChild approach</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acea2483d6f14b4205bd66718df13994/href">https://medium.com/media/acea2483d6f14b4205bd66718df13994/href</a></iframe><p>If you check line 11 and 25 of the code above, you will notice how we create a fake PowersComponent with a fake function that will mock the <em>createFormGroup</em> function using Jasmine’s <strong><em>createSpyObj</em></strong> function.</p><pre>const powersComponent = jasmine.createSpyObj(&#39;PowersComponent&#39;, [&#39;createFormGroup&#39;]);  // line 11<br>...<br>component.powersComponent = powersComponent; // line 25</pre><p>Without the above in the HeroComponent spec file, you will get an error when running the tests that:</p><pre>TypeError: Cannot read property &#39;createFormGroup&#39; of undefined</pre><h3>Implementing a sub-form using the ControlContainer</h3><p>This approach is the confusing one and also has a lot of work, but is also viable.</p><p>In the <em>HeroComponent</em> ‘s template, we have the markup of our other sub-form, the HobbiesComponent</p><pre>&lt;app-hobbies [parentForm]=&quot;heroForm [formGroup]=&quot;heroForm.get(&#39;hobbies&#39;)&quot;<br>&gt;&lt;/app-hobbies&gt;</pre><p>As you can see this form markup uses the <strong>[formGroup] </strong>directive that comes with the <em>ControlContainer</em>, allowing the parent form to pass down a sub-form to the sub-form itself, if needed.<br>Also note that the sub-form is expecting an input which should be the parent form, this also enables us to have access to the parent form within the sub-form if needed, see source of this sub-form below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41fe4e351d4856960b0e0c23ae5a0843/href">https://medium.com/media/41fe4e351d4856960b0e0c23ae5a0843/href</a></iframe><h3>The unit test for this set up is as follows.</h3><p>Create a basic stub of the HobbiesComponent that will be an entry in the declarations for the parent form’s TestBed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abfbe5169b6c016c4b9582f028b804c6/href">https://medium.com/media/abfbe5169b6c016c4b9582f028b804c6/href</a></iframe><p>That’s all we need in the parent form to set up the test for a sub-form using the ControlContainer.</p><p>And below is the spec for the HobbiesComponent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f3ba3bee8393da8a31be14b3ecf8ba8/href">https://medium.com/media/7f3ba3bee8393da8a31be14b3ecf8ba8/href</a></iframe><p>If you look at the source code above, you will see that we are creating a dummy <em>FormGroup</em> using a mock <strong>FormBuilder</strong> defined at line 9. We then use our dummy <em>FormGroup </em>as<em> </em>a<em> </em>token for the ControlContainer on <strong>line 18.</strong></p><p>There are no apparent benefits of using the latter approach, but it works with some drawbacks in respect to maintainability.</p><ul><li>If the sub-form changes, maybe a property name was renamed, the parent form will need to have a sub-form configuration that coincides with that change for the sub-form.</li><li>If the parent form changes on the sub-form configuration, the sub-form will need to know this, so to update the template e.g., <strong><em>formControlName </em></strong>value, or any other code in the sub-form that uses the the sub-form <em>FromGroup’s</em> instance.</li><li>Having to write stubs for all your sub-form components to avoid any warnings in the tests.</li><li>If you want to reuse this form in any other parent form, that form must have a configuration for this sub-form</li></ul><pre>hobbies: this.formBuilder.group({<br>  favoriteHobby: [&#39;&#39;, Validators.required]<br>})</pre><h3><strong>Summary</strong></h3><p>The first approach that uses the the @ViewChild decorator is the best and is entirely reusable and encapsulated and easy to maintain.</p><p>The latter approach works but has many drawbacks.</p><p>But at the end of the day, it is up to you, because its your thinking, your code.</p><p>I hope you enjoyed reading and that you learned something.</p><p>You can checkout the complete source code for this on GitHub</p><p><a href="https://github.com/Teebo/ngx-reusable-forms">Teebo/ngx-reusable-forms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd42e60a8127" width="1" height="1" alt=""><hr><p><a href="https://medium.com/motf-creations/implementing-reusable-and-reactive-forms-in-angular-fd42e60a8127">Implementing reusable and reactive forms in Angular</a> was originally published in <a href="https://medium.com/motf-creations">Motf Creations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>