<?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 Aakash Garg on Medium]]></title>
        <description><![CDATA[Stories by Aakash Garg on Medium]]></description>
        <link>https://medium.com/@aakashgarg19?source=rss-65e2b418dd54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ncWm7Ab-m7XTUBvJsJAAfQ.jpeg</url>
            <title>Stories by Aakash Garg on Medium</title>
            <link>https://medium.com/@aakashgarg19?source=rss-65e2b418dd54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:33:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aakashgarg19/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[The Art of Microfrontends in React with Webpack’s Module Federation]]></title>
            <link>https://blog.devgenius.io/the-art-of-microfrontends-in-react-with-webpack-eeaddc568b79?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeaddc568b79</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 13:52:24 GMT</pubDate>
            <atom:updated>2025-04-02T10:50:53.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvA_Ng7fy_kNNHKH3Jhh_w.jpeg" /></figure><p>When designing a modern web application, you may eventually face a situation where different parts of your UI are managed by different teams, or perhaps you want to independently deploy features without having to rebuild your entire app. This is where <strong>microfrontends</strong> come into play.</p><p>At its core, microfrontends are all about breaking down a large monolithic frontend into smaller, self-contained applications. Each of these applications (or microfrontends) is responsible for a part of the user interface and can be developed, deployed, and updated independently. Sounds neat, right?</p><p>In this article, we’ll dive into how to implement microfrontends in a React app using <strong>Webpack’s Module Federation</strong>. This powerful tool allows different React apps to share components and load them dynamically, making it a perfect match for a microfrontend architecture.</p><h3>Let’s get started!</h3><h3>What are Microfrontends?</h3><p>Microfrontends extend the idea of microservices to the frontend. Instead of having a monolithic frontend, we break it down into smaller, independently deployable pieces. Each microfrontend is a self-contained unit, responsible for a specific feature or section of the UI. This modular approach enables better scalability, allows teams to work on different parts of the application simultaneously, and makes it easier to maintain the app over time.</p><p>In this guide, we’ll explore how to implement microfrontends in a React application using <strong>Webpack’s Module Federation</strong>. This feature allows different applications to share code and load each other dynamically, making it a great fit for a microfrontend architecture.</p><h3>Prerequisites</h3><p>Before we dive in, ensure you have the following:</p><ul><li><strong>Node.js</strong> installed.</li><li>Basic understanding of <strong>React</strong> and <strong>Webpack</strong>.</li><li>Familiarity with <strong>npm</strong> (Node Package Manager).</li></ul><p>We’ll create two simple React applications:</p><ul><li><strong>Host App</strong>: The main container that will load various microfrontends.</li><li><strong>Remote App</strong>: A smaller, self-contained React application that will be loaded dynamically into the Host App.</li></ul><h3>Step 1: Setting Up the Microfrontend Architecture</h3><p>We will start by setting up the <strong>Host App</strong> and the <strong>Remote App</strong>.</p><h4>1.1 Creating the Apps</h4><p>Run the following commands to create both apps using <strong>Create React App</strong>:</p><pre>npx create-react-app host-app<br>npx create-react-app remote-app</pre><p>This will set up two React applications. Next, we will modify the <strong>Webpack</strong> configuration to enable <strong>Module Federation</strong> and allow these apps to communicate.</p><h3>Step 2: Integrating Webpack Module Federation</h3><h4>2.1 What is Webpack Module Federation?</h4><p><strong>Module Federation</strong> is a Webpack feature that allows a JavaScript application to dynamically load code from another application at runtime. This is perfect for microfrontends because it lets us split a large frontend into smaller applications that can be developed, deployed, and updated independently.</p><p>In this step, we’ll configure both the Host App and the Remote App to use Module Federation.</p><h4>2.2 Configuring Webpack for the Host App</h4><p>First, we need to modify the <strong>Host App’s</strong> Webpack configuration to load remote components.</p><ol><li>Install Webpack dependencies:</li></ol><pre>npm install webpack webpack-cli webpack-dev-server --save-dev</pre><p>2. Modify the <strong>webpack.config.js</strong> (create one if it doesn’t exist):</p><pre>const { ModuleFederationPlugin } = require(&quot;webpack&quot;).container;<br>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &#39;host_app&#39;,<br>      remotes: {<br>        remote_app: &#39;remote_app@http://localhost:3001/remoteEntry.js&#39;,<br>      },<br>    }),<br>  ],<br>};</pre><p>This configuration tells the Host App to load the <strong>Remote App</strong> from the URL http://localhost:3001/remoteEntry.js. We will expose the Remote App components in the next step.</p><h4>2.3 Configuring Webpack for the Remote App</h4><p>In the <strong>Remote App</strong>, we need to expose a component that will be used by the Host App.</p><ol><li>Install Webpack dependencies for the Remote App:</li></ol><pre>npm install webpack webpack-cli webpack-dev-server --save-dev</pre><p>2. In the <strong>webpack.config.js</strong> of the Remote App, expose the Button component:</p><pre>new ModuleFederationPlugin({<br>  name: &#39;remote_app&#39;,<br>  filename: &#39;remoteEntry.js&#39;,<br>  exposes: {<br>    &#39;./Button&#39;: &#39;./src/Button&#39;, // Exposing the Button component<br>  },<br>});</pre><p>This configuration will expose the Button component to the Host App via the remoteEntry.js file.</p><h3><strong>Step 3: Sharing Components Between Host and Remote Apps</strong></h3><p>Now, let’s create the components and load them dynamically.</p><h4>3.1 Creating the Remote App’s Button Component</h4><p>In the <strong>Remote App</strong>, create a simple Button component:</p><pre>// src/Button.js<br>import React from &#39;react&#39;;<br><br>const Button = () =&gt; &lt;button&gt;Click Me&lt;/button&gt;;<br><br>export default Button;</pre><h4>3.2 Dynamically Loading the Remote Button in the Host App</h4><p>In the <strong>Host App</strong>, we’ll dynamically load the Button component using React&#39;s Suspense and React.lazy().</p><pre>import React, { Suspense } from &#39;react&#39;;<br><br>const RemoteButton = React.lazy(() =&gt; import(&#39;remote_app/Button&#39;));<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Host App&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;RemoteButton /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>Here, we are dynamically importing the Button component from the Remote App. We wrap the import in Suspense to handle the loading state while the remote module is being fetched.</p><h3>Step 4: Running the Applications</h3><h4>4.1 Running the Remote App</h4><p>To start the Remote App, run the following command in the <strong>remote-app</strong> directory:</p><pre>npm start</pre><p>By default, the app will run on http://localhost:3001. The remoteEntry.js file will be available at this URL.</p><h4>4.2 Running the Host App</h4><p>Next, run the Host App in its own directory:</p><pre>npm start</pre><p>The Host App will run on http://localhost:3000. When you visit this URL, the Host App will dynamically load the Button component from the Remote App.</p><h3>Step 5: Handling Versioning and Updates</h3><h4>5.1 Versioning Microfrontends</h4><p>When you update a microfrontend (like the Remote App), ensure that it maintains backward compatibility with the Host App. If breaking changes occur, update the Host App accordingly to consume the new version of the Remote App.</p><h4>5.2 Caching and Deployment</h4><p>Webpack handles caching of remote modules using hash-based URLs. This helps in ensuring that clients get the correct version of the remoteEntry.js file.</p><p>You can deploy the Remote App to a CDN or a separate server, while the Host App continues to load it dynamically. This makes it easier to update microfrontends independently.</p><h3>Step 6: Deploying the Microfrontends</h3><p>Since microfrontends are self-contained applications, they can be deployed independently. The Host App and Remote App can be deployed to separate servers, cloud environments, or even CDNs. Ensure that the Host App correctly points to the deployed URL of the Remote App in the webpack.config.js.</p><h3>Conclusion</h3><p>Microfrontends offer a powerful approach to managing large-scale frontend applications by breaking them down into smaller, independent units. Using <strong>React</strong> and <strong>Webpack Module Federation</strong>, we can easily implement this architecture and enjoy the benefits of better maintainability, scalability, and independent deployments.</p><p>However, there are challenges to consider, such as managing shared state between microfrontends and ensuring that network requests are optimized for performance. With careful planning and proper tooling, microfrontends can significantly improve the development process and user experience.</p><p><em>By following these steps, you should now have a solid understanding of how to implement microfrontends in React with Webpack. It’s a powerful architecture that can make your frontend apps more modular and easier to manage.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeaddc568b79" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/the-art-of-microfrontends-in-react-with-webpack-eeaddc568b79">The Art of Microfrontends in React with Webpack’s Module Federation</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing An Application From Open Source Vulnerabilities]]></title>
            <link>https://blog.devgenius.io/securing-an-application-from-open-source-vulnerabilities-5aae108590d9?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aae108590d9</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 16:38:01 GMT</pubDate>
            <atom:updated>2022-02-15T16:38:01.799Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7RJoSt2RqzBjShOaCKvTQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Shahadat Rahman</a> on <a href="https://unsplash.com/s/photos/open-source?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>With the increased usage of open source solutions and acceptance of third-party libraries in the majority of applications. It has become more important to secure our applications not only from vulnerabilities that our code might introduce but also secure it from vulnerabilities that can be induced by the code that comes with open source libraries we add into our application.</p><p>Recently the whole industry was shocked when there were serious vulnerabilities reported in a package, that was used in most of the java applications for logging i.e. log4j. The impact was wide because of wider usage, and even the fix of vulnerability was made available ASAP because of an active community and package maintainers.</p><p>This was a case where the vulnerability was unknown to anyone before it was reported. But we do have cases where applications are using a version of a dependency on which there are serious vulnerabilities already reported.</p><p>Securing the web application in such cases depends on various factors.</p><p>It starts with choosing the right dependency for your project which can be decided on the following factors:-</p><ol><li>Choosing a dependency that has many downloads.</li></ol><p>For solving a problem there can be multiple libraries available. When choosing one, how much audience is using a particular library should be a factor while deciding the one we are opting to use in our application.</p><p>2. Number of Contributors</p><p>The bigger the community the better the chances of getting support for bug and security fixes. Hence while choosing a package, a key factor to notice is the number of contributors and maintainers for a package.</p><p>3. Release Pattern</p><p>It&#39;s quite possible that a package is very famous but for a long time, there are no latest releases around that package. We might notice a very big community for a package because of it being widely used in past. Hence checking whether the package is still having releases in recent times will add to the surety of picking that package.</p><p>4. Checking the version you choose for vulnerabilities</p><p>You have picked up a package with the latest version, as that was the best choice available based on the points above. But still, you might check whether that version has some vulnerabilities already reported or not. Here you need to explore security advisory pages where such vulnerabilities are reported. For eg:-</p><ul><li><a href="https://github.com/advisories">GitHub Advisory Database</a></li><li><a href="https://www.cvedetails.com/vulnerability-list/">CVE security vulnerability database. Security vulnerabilities, exploits, references and more</a></li></ul><p>Such advisories can help you out to look for already reported vulnerabilities.</p><blockquote><strong>Choosing a dependency based on above points is very critical, because if above points are followed properly. There is a good chance that if a vulnerability is reported in future in any of the packages you are using. You will be getting a fix around that as soon as possible.</strong></blockquote><p>Now you chose a dependency depending on the points above. At the time of adding it, the dependency and the version picked didn’t have any reported vulnerabilities. But as time progresses we need to make sure that the investigation we did while adding still holds true in the current scenario.</p><p>There are many things which can be done to take care of this.</p><ol><li>Auditing your application periodically.</li></ol><p>Many dependency managing solutions now come with an inbuilt vulnerability scanner for added dependencies in your project. Such scanners basically check all the packages added against one of the advisory repositories like the ones I shared above. For example, with <strong>npm</strong> you can run the following command to know such vulnerabilities</p><blockquote>npm audit</blockquote><p>Your can read more about npm audit here :-</p><p><a href="https://blog.npmjs.org/post/173719309445/npm-audit-identify-and-fix-insecure.html">npm Blog Archive: `npm audit`: identify and fix insecure dependencies</a></p><p>2. DevSecops</p><p>You can make auditing part of your build pipelines. Tools like Jenkins comes with plugins which you can add to your pipeline to do a deep scan of your application and let you know about present vulnerabilites. Different thresholds can be set to basically fail the build if reported vulnerabilities are more than the threshold set.</p><p>3. Timely Dependency Updates</p><p>It&#39;s crucial to keep a dependency on the latest versions possible. As latest versions usually come with bug fixes and security fixes. In such upgrades, the dependencies usually also upgrade the internal packages they are using. So if possible we should keep the dependencies we are using to the latest version possible.</p><blockquote><strong>In case, lets say after getting an audit report for a package you feel that the package being used is not actively maintained now and the chances of getting a fix around that vulnerability is very small. Then its good time to look for an alternate package following the points which we already discussed above.</strong></blockquote><p>Doing this might not serve as a silver bullet against unknown vulnerabilities, but will surely help us avoid vulnerabilities that are out in public and known to a wider audience. As the vulnerability that is out there in public, have more chance of being tried and exploited by a wider audience with malicious intent.</p><blockquote><strong>I have tried to cover the points I could think through, will add if find a valid point in comments to this article. Keep reading, keep learning, keep growing.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aae108590d9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/securing-an-application-from-open-source-vulnerabilities-5aae108590d9">Securing An Application From Open Source Vulnerabilities</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive Into Structural Directives In Angular]]></title>
            <link>https://blog.devgenius.io/deep-dive-into-structural-directives-in-angular-8a5d0251fbb5?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a5d0251fbb5</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 22:53:02 GMT</pubDate>
            <atom:updated>2021-06-12T22:53:02.388Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*VWYUHrATqLu8l-sR" /></figure><p>Lets start discussing from types of directives available in Angular. There are two types of directives available in Angular.</p><ol><li><strong>Structural Directives</strong></li></ol><p>Structural directives are the directives which can change the structure of DOM and perform DOM manipulations.</p><p><strong>2. Attribute Directives</strong></p><p>Attribute directives are the directives that can change the appearance or behavior of DOM elements and Angular components</p><p>This article is all about the structural directives. Angular provides few inbuilt structural directives like NgIf, NgFor and NgSwitch. Let’s see an example of NgIf below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05dac64cef642532b052a2af25e0aa65/href">https://medium.com/media/05dac64cef642532b052a2af25e0aa65/href</a></iframe><p>NgIf is a directive, that displays the element on which its attached only if the condition passed to it is truthy. But lets look at the syntax of it closely. In Angular the directive is named only as ngIf. But here we are using it with an asterisk(*).</p><p>As per Angular’s official documentation :-</p><blockquote>The asterisk, <strong>*</strong>, syntax on a structural directive, such as <strong>*ngIf</strong>, is shorthand that Angular interprets into a longer form. Angular transforms the asterisk in front of a structural directive into an <strong>&lt;ng-template&gt;</strong> that surrounds the host element and its descendants.</blockquote><p>So, as per this statement, Angular will interpret our DOM in code snippet above as given below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/917c8135de5529f2170730e5fdab3657/href">https://medium.com/media/917c8135de5529f2170730e5fdab3657/href</a></iframe><p>So even if you write your code in form of ng-template its same as writing *ngIf on a div. But let’s understand why Angular does that.</p><p>To understand that let’s try to create a similar directive. If we look at ngIf directive closely, it removes the particular DOM element if condition is falsy. But if we apply this directive on a component selector in template, that will destroy the component if condition become falsy. So lets try to solve this problem by creating a structural directive known as ngShow, which will remove the element from DOM but won’t destroy and recreate it subsequent value changes. Instead it will re add the same instance.</p><p>Let’s create this directive step by step.</p><ol><li>Run command.</li></ol><p><em>ng generate directive ngShow</em></p><p>2. Our file will look like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c69e9839d756de4d80895d8b77ac14/href">https://medium.com/media/32c69e9839d756de4d80895d8b77ac14/href</a></iframe><p>3. Let’s inject templateRef and viewContainerRef in the directive and introduce an input known as ngShow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79559618f3bc889d443f81811a884444/href">https://medium.com/media/79559618f3bc889d443f81811a884444/href</a></iframe><p>This is the main reason why Angular interprets Structural Directives in form of ng-template, so that it can dynamically embed an template or remove it on the basis of condition. And ViewContainerRef is the reference of the container where the template will be created.</p><p>4.<strong> </strong>Now lets implement our directive such that once created an template, after further value changes for condition, it reuses the same template instead of destroying and re-creating.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89907533db0802a9d51ff480c649e023/href">https://medium.com/media/89907533db0802a9d51ff480c649e023/href</a></iframe><p>Now if look closely at line#23 we are storing a reference of view creating when the condition was true first time and then we are detaching the view when condition is false.</p><p>What detach does is it prevents destroy of the view and simply just remove it. And then later we are re-inserting that same viewRef for subsequent truthy values of the condition. We are only destroying that view when directive is destroyed.</p><p>5. Now let’s use this directive in same example of app component instead of ngIf on the div.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6925a50d01eb6fe86c560df1486a3ed/href">https://medium.com/media/d6925a50d01eb6fe86c560df1486a3ed/href</a></iframe><p>This will show and hide the Hello text every 2000 seconds without destroying the DOM node and same will apply if we put this directive on a component selector in template.</p><p>Currently, this directive won’t support else like behavior which we have in ngIf directive, but if we want we can configure that as well by adding one more input to the directive and apply same principles. But ngShow simply means to hide the element if condition is falsy. Thats why that isn’t done here.</p><blockquote>Structural directives are one of the nice features to perform DOM manipulations in angular. And if we understand them enough we can create our own structural directives for different scenarios to perform DOM manipulations.</blockquote><p>To know more about structural directives, you can also follow official documentation here :- <a href="https://angular.io/guide/structural-directives">https://angular.io/guide/structural-directives</a></p><p>Different types of structural directives can be created by following it, even something like ngFor is based on same type of setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a5d0251fbb5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/deep-dive-into-structural-directives-in-angular-8a5d0251fbb5">Deep Dive Into Structural Directives In Angular</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most Common Errors Encountered In Angular With Solution]]></title>
            <link>https://blog.devgenius.io/most-common-errors-encountered-in-angular-with-solution-53e1f774c3d5?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e1f774c3d5</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 12:48:06 GMT</pubDate>
            <atom:updated>2021-04-19T12:48:06.990Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*GgaZut67iGJZQX2o" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clément Hélardot</a> on <a href="https://unsplash.com/s/photos/development?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>While coding we tackle issues on a daily basis. Some of which are functional bugs and some of which are technical issues. Functional bugs is something which is mostly related to gap between what was expected out of the implementation and what is actually implemented. Which is generally simpler to identify and fix.</p><p>But technical issues are the one which can be quite challenging sometimes and you might spend days to find appropriate solutions for them. Today we will be talking about few Errors you might encounter while using Angular for development.</p><p>It will include such errors which a Angular developer will most probably face and it will be helpful to know its solution. So will be including the possible solution for it.</p><p>Let’s get into it and start understanding about the most commonly encountered errors in Angular.</p><ol><li><strong>ExpressionChangedAfterItHasBeenCheckedError</strong></li></ol><p>In dev mode, Angular performs an additional check after each change detection run, to ensure the bindings haven’t changed. This catches errors where the view is left in an inconsistent state.</p><p>By inconsistent, we mean here is that while checking angular finds that value of that binding is different from what was rendered by rendering engine.</p><p>Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop.</p><p>It is common when dealing with loading status and asynchronous operations, a child component changes its parent bindings, or changing something in lifecycle hooks.</p><p>You won’t get this error in production mode as the additional check we mentioned above is only for dev mode. Many developers ignore this error because of this. But ignoring this will lead you into bugs where screen is showing wrong data.</p><p><strong>Possible Solution</strong></p><p>Generally, it could be fixed by updating binding properly and at right time. But if you feel that your implementation couldn’t be the reason of this. You can inject <strong>ChangeDetectorRef</strong> in your component and call its <strong>detectChanges</strong> method after updating the binding which is giving you the error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73fb41ca9627a89c49e1fd721bf3b6e0/href">https://medium.com/media/73fb41ca9627a89c49e1fd721bf3b6e0/href</a></iframe><p><strong>2. NG0200: Circular dependency in DI detected while instantiating a provider</strong></p><p>A cyclic dependency exists when a dependency of a service directly or indirectly depends on the service itself. For example, if <strong>DataService </strong>depends on <strong>ProductService</strong>, which also depends on <strong>DataService</strong>. Angular will have to instantiate <strong>ProductService</strong> to create <strong>DataService</strong>, which depends on <strong>DataService</strong>, itself.</p><p><strong>Possible Solution</strong></p><p>The statement explains the problem itself, you need to resolve the interdependency here.</p><p>Break this loop (or circle) of dependency to resolve this error. This most commonly means removing or refactoring the dependencies to not be reliant on one another.</p><p><strong>3. NG0201: No provider for {token} found!</strong></p><p>You see this error when you try to inject a service but have not declared a corresponding provider. A provider is a mapping that supplies a value that you can inject into the constructor of a class in your application.</p><p><strong>Possible Solution</strong></p><p>To fix the error ensure that your service is registered in the list of providers of an <strong>NgModule</strong> or has the <strong>Injectable</strong> decorator with a <strong>providedIn</strong> property at top.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f3a9c7950ded614934c6471fcd06fe6/href">https://medium.com/media/1f3a9c7950ded614934c6471fcd06fe6/href</a></iframe><p><strong>4. NG1001: Decorator argument is not an object literal</strong></p><p>This is a new error, and have been introduced with Ivy being used as rendering engine instead of ViewEngine.</p><p>This is an intentional change in Ivy, which enforces stricter argument requirements for decorators than View Engine. Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c64db0880645d73c99286227075cff/href">https://medium.com/media/96c64db0880645d73c99286227075cff/href</a></iframe><p><strong>5. Cannot bind to ngModel</strong></p><p>You will get this error while trying to use ngModel on a element and you don’t have FormsModule or ReactiveFormsModule imported in your module of which your component is part of.</p><p><strong>Possible Solution</strong></p><p>You need to import FormsModule or ReactiveFormsModule into that particular module depending on type of Forms you are using</p><p><strong>6. Cannot read property * of undefined</strong></p><p>Above * can be any property you are trying to use. This error means when you are trying to read a property from an object, that object is undefined and JS engine can’t read that particular property.</p><p><strong>Possible Solution</strong></p><p>If error is originating from your typescript code, try to make your code undefined/null safe by putting if conditions.</p><p>If its originating from your template, and you want to only show field if its available you can use *ngIf directive and if you want to show blank if field is blank, then you can use elvis operator to show that field and make it undefined/null safe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37206dc111047950b014c430fe59f31f/href">https://medium.com/media/37206dc111047950b014c430fe59f31f/href</a></iframe><p><strong>7. Not Found Error</strong></p><p>Sometimes you will get Pipe not found or Export not found error. This generally means you have missed the import of that directive, pipe in NgModule where it should have been.</p><p><strong>Possible Solution</strong></p><p>Include that Pipe/Directive in particular NgModule declarations array.</p><p>8. <strong>Component is not part of any NgModule</strong></p><p>The error explains itself, and is somewhat similar to previous error. The inclusion of component is missing from declarations array of NgModule or its not exported via particular module which you have imported in your current NgModule.</p><p><strong>Possible Solution</strong></p><p>Include that Pipe/Directive in particular NgModule declarations array or export from that particular module from which you want to share with other modules.</p><blockquote>The list above tries to accommodate list of errors which you might encounter in any Angular application. Hope the above list helps and makes it easy to solve the errors when you face them next time. If you feel any other error needs to be part of this list, do leave it in comments and I will try to add it in this list or write a part 2 of same topic.</blockquote><blockquote>Although there are more errors which could be covered here, but the focus was on generic errors which are common in most of cases. If you are facing any other issue, you can check Error Reference section under Reference section in Angular’s Official Documentation website :- <a href="https://angular.io/">https://angular.io</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e1f774c3d5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/most-common-errors-encountered-in-angular-with-solution-53e1f774c3d5">Most Common Errors Encountered In Angular With Solution</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Future Of Angular After Version 11]]></title>
            <link>https://blog.devgenius.io/future-of-angular-after-version-11-912cdbbd17d8?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/912cdbbd17d8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 13:33:37 GMT</pubDate>
            <atom:updated>2021-02-03T13:33:37.789Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*cjULZPyFZnJUsMt4" /><figcaption>Photo by <a href="https://unsplash.com/@jerrykavan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jaromír Kavan</a> on <a href="https://unsplash.com/s/photos/roadmap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We have been seeing two releases each year with major updates related to performance and features in Angular since Angular 2. From being a framework which is heavy and takes too much time for <strong>First Contentful Paint (FCP) </strong>to one which is much more stable and performant in terms of FCP.</p><p>During the course of journey Angular improved as an framework in every aspect. Whether its performance, features, practices, guidelines, scalability, it has become one of the ideal choices for a large scale Enterprise application.</p><p>Angular team has been releasing major features with each release, while ensuring there are minimal backward compatibility issues and updating to new version is easy. We have seems some great improvements in area of build times, development tooling, testing, build size etc.</p><p>It has been great, but after all that since Angular has now became a mature framework, what can we expect next from the upcoming releases of Angular, since most of the options we might want from an web application are now provided by the framework. To understand it better, we should have a look at the future roadmap published by Angular team. Which will give us a realistic expectation around what to expect next. Lets have a look at those points one by one.</p><p><strong>1. Better developer ergonomics with strict typing for </strong><strong>@angular/forms</strong></p><p>Work on implementing stricter type checking for reactive forms. This will allow developers to catch more issues during development time, enable better text editor and IDE support, and improve the type checking for reactive forms.</p><p><strong>2. Leverage full framework capabilities with Zone.js opt-out</strong></p><p>Design and implement a plan to make Zone.js optional from Angular applications. This will simplify the framework, improve debugging, and reduce application bundle size. Additionally, this will allow us to take advantage of native async/await syntax, which currently Zone.js does not support.</p><p>Currently Zone.js is the magic which allows to re-render the template by detecting changes. Let’s see what Angular team comes with as a solution after one choose to opt-out of Zone.js</p><p><strong>3. Reduce framework overhead by removing legacy View Engine</strong></p><p>After the transition of all our internal tooling to Ivy has completed, we want to remove the legacy View Engine for smaller Angular conceptual overhead, smaller package size, lower maintenance cost, and lower complexity of the codebase.</p><p>We all know the benefits of Ivy and specifically its the way to go with while using the latest versions of Angular. But this is a point to consider for Applications which have updated to latest version of Angular but are keeping enableIvy as false. They should update their application use ivy soon because in future they might not be able to update to latest versions if they don’t start using ivy.</p><p><strong>4. Improved test times and debugging with automatic test environment tear down</strong></p><p>To improve test time and create better isolation across tests, we want to change TestBed to automatically clean up and tear down the test environment after each test run.</p><p>This will improve developer’s productivity and will also reduce build times where tests are part of build pipeline.</p><p><strong>5. Improved build performance with ngc as a tsc plugin distribution</strong></p><p>Distributing the Angular compiler as a plugin of the TypeScript compiler will substantially improve developers’ build performance and reduce maintenance costs.</p><p><strong>6. Support adding directives to host elements</strong></p><p>A long-standing feature request is to add the ability to add directives to host elements. The feature will allow developers to augment their own components with additional behaviors without using inheritance. The project will require substantial effort in terms of the definition of APIs, semantics, and implementation.</p><p>Currently you can’t add directives to host element. But you can style it by using :host CSS selector. As the selector of the component also becomes a DOM element, being able to add directives to that element will allow to have more possibilities.</p><p><strong>7. Simplified Angular mental model with optional NgModules</strong></p><p>To simplify the Angular mental model and learning journey, we’ll be working on making NgModules optional. This work will allow developers to develop standalone components and implement an alternative API for declaring the component’s compilation scope.</p><p>Although this will be a major change and might not be possible for existing applications to migrate to this. But this will definitely allow developers to have a fine grain control over compilation scope for a particular component without thinking much about which NgModule they should belong to. But saying this right now will be too early, it will be more clear once Angular team release it and we get some time to try building few Apps without NgModules.</p><p><strong>8. Ergonomic component level code-splitting APIs.</strong></p><p>A common problem of web applications is their slow initial load time. A way to improve it is to apply more granular code-splitting on a component level. To encourage this practice, we’ll be working on more ergonomic code-splitting APIs.</p><p>Kudos to this hence this will mean smaller build and faster launch time i.e. improved FCP.</p><blockquote>This all seems cool, hence this will mean Angular becoming more robust and applications build on Angular being more performant. But this is what future of Angular promises, which doesn’t mean this all will be part of Angular 12 itself.</blockquote><p>Let’s have a look at few of the things which are In Progress and might be part of recent future releases of Angular.</p><p><strong>1. Faster apps by inlining critical styles in Universal applications</strong></p><p>Loading external stylesheets is a blocking operation, which means that the browser can’t start rendering your application until it loads all the referenced CSS. Having render-blocking resources in the header of a page can significantly impact its load performance, for example, its FCP.</p><p><strong>2. Improve debugging with better Angular error messages</strong></p><p>Error messages often bring limited actionable information to help developers resolve them. Angular team have been working on making error messages more discoverable by adding associated codes, developing guides, and other materials to ensure a smoother debugging experience.</p><p><strong>3. Transition the Angular language service to Ivy</strong></p><p>The goal of this project is to improve the experience and remove legacy dependency by transitioning the language service to Ivy. Today the language service still uses the View Engine compiler and type checking, even for Ivy applications. Angular Team wants to use the Ivy template parser and improved type checking for the Angular Language service to match application behavior. This migration will also be a step towards unblocking the removal of View Engine, which will simplify Angular, reduce the npm package size, and improve the framework’s maintainability.</p><p><strong>4. Increased security with native Trusted Types in Angular</strong></p><p>In collaboration with Google’s security team, Angular team is adding support for the new Trusted Types API. This web platform API will help developers build more secure web applications.</p><p><strong>5. Enhanced Angular Material components by integrating MDC Weblink</strong></p><p>MDC Web is a library created by Google’s Material Design team that provides reusable primitives for building Material Design components. The Angular team is incorporating these primitives into Angular Material. Using MDC Web will align Angular Material more closely with the Material Design specification, expand accessibility, improve component quality, and improve our team’s velocity.</p><p><strong>6. Optimized build speed and bundle sizes with Angular CLI webpack 5</strong></p><p>As the v11 release, introduced an opt-in preview of webpack 5 in the Angular CLI. To ensure stability, will continue iterating on the implementation to enable build speed and bundle size improvements.</p><p><strong>7. Accelerated debugging and performance profiling with Angular DevTools</strong></p><p>Working on development tooling for Angular that will provide utilities for debugging and performance profiling. This project aims to help developers understand the component structure and the change detection in an Angular application.</p><p>I have tried to mention most of points with what I think will be their impact on development of applications and their performance. Hope this helps in determining what to expect from upcoming releases. All the points mentioned above are referred from official roadmap from Angular team, so we can expect most of these points to make it to future releases unless they find something not technically feasible like it happened with using Bazel for build pipeline.</p><blockquote>There are more In Progress points, out of which few are for internal improvements like improving Angular team’s performance dashboards etc. As main focus of this article was related to points which will impact application development and its performance. If you want to know all points you can refer to Official Roadmap published on Angular’s Official Documentation :- <a href="https://angular.io/guide/roadmap">https://angular.io/guide/roadmap</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=912cdbbd17d8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/future-of-angular-after-version-11-912cdbbd17d8">Future Of Angular After Version 11</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Schematics For Your Application In Angular]]></title>
            <link>https://blog.devgenius.io/custom-schematics-for-your-application-in-angular-f691f6fd4dc?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/f691f6fd4dc</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 22:11:36 GMT</pubDate>
            <atom:updated>2021-01-01T22:11:36.650Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dJc47_JCaH38HpEROrlAA.png" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@lucabravo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Luca Bravo</strong></a><strong> on </strong><a href="https://unsplash.com/s/photos/magic-code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><strong>Unsplash</strong></a></figcaption></figure><p>Schematics, what are they and how they can be useful is very important to understand when you trying to lay down a foundation for a large scale project. Let’s read the official definition first.</p><blockquote>A schematic is a template-based code generator that supports complex logic. It is a set of instructions for transforming a software project by generating or modifying code.</blockquote><blockquote>The schematic collection can be a powerful tool for creating, modifying, and maintaining any software project, but is particularly useful for customizing Angular projects to suit the particular needs of your own organization. You might use schematics, for example, to generate commonly-used UI patterns or specific components, using predefined templates or layouts. You can use schematics to enforce architectural rules and conventions, making your projects consistent and inter-operative.</blockquote><p>All of us while using Angular have came across Angular CLI commands. When you use generate command to generate a component, behind the scenes a schematic is used to define what should be put into that newly created typescript file based on different flags you provide.</p><p>Let’s take a scenario where we want to add a copyright file header whenever we generate a component. This is a very common scenario that we may want in a corporate project. For eg:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35eba26aa4ccf06cba9b4fed5cd02202/href">https://medium.com/media/35eba26aa4ccf06cba9b4fed5cd02202/href</a></iframe><p>To this automatically, we can create a schematic which will be used for component generation and will attach that header automatically to avoid developers missing this in components.</p><p>Let’s create such schematic step by step.</p><ol><li><strong>Schematics CLI.</strong></li></ol><p>Schematics come with their own command-line tool. Using Node 6.9 or above, install the Schematics command line tool globally:</p><blockquote><em>npm install -g </em><a href="http://twitter.com/angular"><em>@angular</em></a><em>-devkit/schematics-cli</em></blockquote><p><strong>2. Create a Angular Workspace</strong></p><p>Create a new angular workspace for having our library with following command.</p><blockquote>ng new header — createApplication=false</blockquote><p><strong>3. Create a Angular Library</strong></p><p>Create a library inside that workspace with following command.</p><blockquote>ng generate library file-header</blockquote><p><strong>4. Creation of schematics folder</strong></p><p>In your library’s root folder create a folder named schematics. Also create a <strong>collection.json</strong> file inside that folder for creation of schematic collection with following content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/946cb688c21d8e7fb978d784cf9abffe/href">https://medium.com/media/946cb688c21d8e7fb978d784cf9abffe/href</a></iframe><p><strong>5. Creation of schema.json</strong></p><p>Create a folder named component-header inside schematics folder and add a file schema.json in that folder with following content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1562e7c8b534c90f89406e0f215edc8e/href">https://medium.com/media/1562e7c8b534c90f89406e0f215edc8e/href</a></iframe><ul><li><em>id</em>: A unique id for the schema in the collection.</li><li><em>title</em>: A human-readable description of the schema.</li><li><em>type</em>: A descriptor for the type provided by the properties.</li><li><em>properties</em>: An object that defines the available options for the schematic.</li></ul><p><strong>6. Creation of schema.ts</strong></p><p>Create schema.ts where you created schema.json for current schema. It defines an interface that stores the values of the options defined in the schema.json file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c18c02066196f6288f2134236e042032/href">https://medium.com/media/c18c02066196f6288f2134236e042032/href</a></iframe><p><strong>7. Add Template Files</strong></p><p>Create a files folder inside component-header folder. After that create files named</p><p>__name@dasherize__.component.ts.template, __name@dasherize__.component.html.template, __name@dasherize__.component.css.template</p><p>with following content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1ab412b536662b433abafc8257e542/href">https://medium.com/media/9e1ab412b536662b433abafc8257e542/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e597d01fe0c46ad5e04e529ee9d1007/href">https://medium.com/media/5e597d01fe0c46ad5e04e529ee9d1007/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/711f3a4f7cef8f7ab66a9d790a516df0/href">https://medium.com/media/711f3a4f7cef8f7ab66a9d790a516df0/href</a></iframe><p><strong>8. Add Rule Factory</strong></p><p>Create a index.ts file where schema.json was created and then add rule factory to it like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f81eae0f7c6626c0fd589d3673cbe9a/href">https://medium.com/media/2f81eae0f7c6626c0fd589d3673cbe9a/href</a></iframe><p><strong>9. Define Generation Rule</strong></p><p>Now we will create a generation rule to use our template files and create component files for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b909a5f1cf299b6ef9e4a793553d652/href">https://medium.com/media/2b909a5f1cf299b6ef9e4a793553d652/href</a></iframe><p>To understand different parts of this code you can refer to Angular’s Official Documentation <a href="https://angular.io/guide/schematics-for-libraries#define-a-generation-rule">Schematic Rule Generation</a>.</p><p><strong>10. Update collection.json with schema</strong></p><p>Update collection.json with this newly created schematic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd581630bf84ccd771d6a821076a772b/href">https://medium.com/media/cd581630bf84ccd771d6a821076a772b/href</a></iframe><p><strong>11. Update package.json of library.</strong></p><p>Update package.json inside projects\file-header with content below and run npm install.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b75cdb9cdabcd877fde5e8e7e4b9b59/href">https://medium.com/media/8b75cdb9cdabcd877fde5e8e7e4b9b59/href</a></iframe><p><strong>12. Create tsconfig.schematics.json</strong></p><p>Create tsconfig.schematics.json in root of your library with following content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c836020bcfc77c020111cdbf6beeb81a/href">https://medium.com/media/c836020bcfc77c020111cdbf6beeb81a/href</a></iframe><p><strong>13. Create Gulpfile</strong></p><p>Gulpfile at root of library for copying schematics in dist folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05c8d26639cd22be6e7ab9865bb3b011/href">https://medium.com/media/05c8d26639cd22be6e7ab9865bb3b011/href</a></iframe><p><strong>14. Create Application</strong></p><p>Create application inside same workspace to use this schematic collection using following command.</p><blockquote>ng generate application my-first-app</blockquote><p><strong>15. Build and link library</strong></p><p>Build library using command</p><blockquote>ng build file-header</blockquote><p>Then go inside projects/file-header folder and run command</p><blockquote>npm run build</blockquote><p>Then we need to link this library from root of workspace i.e. our header folder. To link we need to run command</p><blockquote>npm link file-header</blockquote><p><strong>16. Start using schematic</strong></p><p>You can use this schematic now in my-first application you just created in step 14 by command.</p><blockquote>ng generate file-header:component-header</blockquote><p>Where file-header was library name and component-header was our schematic name.</p><p>It will give you output like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*_R9oKxUZxWCPRVB5nTl_eQ.png" /></figure><p>With typescript file now having header like we wanted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/526cd602cbdd2107099dda0cb40aac5b/href">https://medium.com/media/526cd602cbdd2107099dda0cb40aac5b/href</a></iframe><blockquote>Multiple schematics can now be added to same collection which can be used to enforce certain practices to the project and to do those things automatically.</blockquote><p>The example shown describes schematic for generation. You can also create schematic for update as well. These can be pretty handy if you are publishing a library to support backward compatibility.</p><p>Angular uses schematics for various things. When you run <strong>ng update</strong> to update angular dependencies there are multiple schematics that run behind the scenes to update your code automatically</p><blockquote>Note:- Angular CLI’s generate command supports various flags and options while creating component and also it update the module automatically which our schematics doesn’t do in this example. As this example was more focused on giving an idea about how to create an schematic. To see source of CLI’s official source for generate component command you can visit their Github link :- <a href="https://github.com/angular/angular-cli/tree/master/packages/schematics/angular/component">https://github.com/angular/angular-cli/tree/master/packages/schematics/angular/component</a></blockquote><blockquote>For knowing how to create different types of schematic apart from generate, you can visit Angular’s official documentation :- <a href="https://angular.io/guide/schematics">https://angular.io/guide/schematics</a></blockquote><blockquote>To see complete source of the example mentioned above you can visit my github repository :- <a href="https://github.com/aakashgarg19/header">https://github.com/aakashgarg19/header</a></blockquote><blockquote>Schematics can deliver endless possibilities for an application and various activities which were repeated by developers can be automated if they are used wisely. As once schematic is developed, its just a command which will do all the hard work for you.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f691f6fd4dc" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/custom-schematics-for-your-application-in-angular-f691f6fd4dc">Custom Schematics For Your Application In Angular</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Preloading Strategy For Large Applications In Angular]]></title>
            <link>https://blog.devgenius.io/advanced-preloading-strategy-for-large-applications-in-angular-cd7ac2b763af?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd7ac2b763af</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 08:31:00 GMT</pubDate>
            <atom:updated>2020-11-09T08:31:00.470Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*j7JmPgYZY4-Ry12X" /><figcaption><strong>City Image By </strong><a href="https://unsplash.com/@marcojodoin"><strong>Marc-Olivier Jodoin</strong></a><strong> on Unsplash</strong></figcaption></figure><p>In Most of the applications we have a requirement of preloading modules before user navigates to a particular page to reduce loading time. In this article we will not be talking about inbuilt preloading support provided by Angular, or the ones using PreloadingStrategy. Instead we will be talking about implementing something that is more suitable for a large scale application and something which is progressive and scalable.</p><p>But, before continuing with that let’s discuss the problem with approaches that is already available via implementing Preloading Strategy</p><p>PreloadingStrategy interface of angular asks us to implement a preload method and in custom strategy we can decide on the basis if our route have specific boolean flag which asks for something like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5946a9b12119ad8123d0ce632fa1e74/href">https://medium.com/media/c5946a9b12119ad8123d0ce632fa1e74/href</a></iframe><p><strong>The Problem</strong></p><ol><li>In case of too many modules, we have to define on app bootstrap what we want to preload. That will block the network for preloading blocking other resources which we might want to load.</li><li>It will try to preload load all with preload flag even when user might not even visit their parent route.</li><li>As the scale of application will increase, there will be too much preloading happening on bootstraping of application.</li><li>Preloading so much in beginning can be too much network/data intensive, which might not suit that well for mobile device users.</li></ol><p>Let’s take a scenario that we have nested routes in which some lazy loaded routes are at parent level, and some lazy loaded routes in child routes of lazy loaded modules like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ce6b5a0aab872b0e37a36a9413aef88/href">https://medium.com/media/9ce6b5a0aab872b0e37a36a9413aef88/href</a></iframe><p>Now if we only want to preload dashboard if user visits admin route so that dashboard module is ready before user visits dashboard, that is not something which is controllable by PreloadingStrategy.</p><p>So, in general our expectation is to apply preloading on children routes only if user visits parent because this kind of nesting can be of any level and it only makes sense in case of large applications of whatever which really might be required in near possible user journey instead of preloading all decided in the beginning.</p><p>Hence its not possible via PreloadingStrategy, we can achieve it via having some handling of it in AppComponent by having something like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dce5ba109a144ebb0f98f0a4c1f48d7/href">https://medium.com/media/8dce5ba109a144ebb0f98f0a4c1f48d7/href</a></iframe><p>So, what we are doing here is listening to NavigationEnd event of router and then checking children routes of currently activated route. Because now loadChildren attribute of a route accepts a callback for loading a particular module, we can directly call it if its present.</p><p>This will help us to load all children modules once parent is activated, but only the ones without canActivate Guard but this can be changed and modified as per application requirement.</p><p>But, now let’s say we only wanted to preload 3 out of 5 children routes with lazy loaded modules, that can also be achieved by tweaking our code and routes. Let’s change our route to something like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a0ee7b24719eccc414fe5798938cabd/href">https://medium.com/media/0a0ee7b24719eccc414fe5798938cabd/href</a></iframe><p>If we look closely, we have added a preload flag to dashboard route in data properties which we don’t have in manage route. So, now what we are expecting is only to preload dashboard route when admin route is visited and to skip manage route from preloading. Let’s look at how we can achieve that by tweaking our code in AppComponent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81fd6cde43e0abcb38643d184f225fbf/href">https://medium.com/media/81fd6cde43e0abcb38643d184f225fbf/href</a></iframe><p>We have just added a check for preload property in our if condition and now it will only preload the children modules which have preload as true in children routes.</p><p>After doing the above we have best of both the worlds. Because now we are preloading only what might be required in nearby future and its something which is progressive and scalable. Also we are not blocking the network by preloading everything in beginning.</p><p>This strategy is one of the customization which was not possible via PreloadStrategy and can be tweaked as per improvements you want on top of this.</p><p>Hope it helps and Kudos to better preloading in your upcoming applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd7ac2b763af" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/advanced-preloading-strategy-for-large-applications-in-angular-cd7ac2b763af">Advanced Preloading Strategy For Large Applications In Angular</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Angular Applications Like A Pro]]></title>
            <link>https://blog.devgenius.io/debugging-angular-applications-like-a-pro-514e7bff95f6?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/514e7bff95f6</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 08:29:46 GMT</pubDate>
            <atom:updated>2020-10-27T08:29:46.396Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*iq2Ea6wOBGuP5XTP" /><figcaption><strong>Debugging Image From Unsplash By </strong><a href="https://unsplash.com/@nubelsondev"><strong>Nubelson Fernandes</strong></a></figcaption></figure><p>Every now and then we get caught up in strange issues with our angular components and one way to debug is of course to use breakpoints in DevTools or IDE. But they can help your inspect a piece of code when its called like methods and all.</p><p>But what about let’s say I want to see the current value of a property and re-render a Angular component which is using OnPush strategy to see if calling applyChanges render actual value on the ui. Yes, you can have console logs in your code and try to put applyChanges in code and then see the updates. But wouldn’t it take less time, if we could do these from the browser itself.</p><p>Let’s take an example, you are rendering a component in ngFor, so there are multiple instances of same component. For example :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd95d5aaa5603370bbe666ebee7536f/href">https://medium.com/media/dbd95d5aaa5603370bbe666ebee7536f/href</a></iframe><p>So, there were 10 employee components rendered, and you want to see the employee property value of one with id as emp-4 only. Wouldn’t it be much easier to find the component instance from element and then see the property value in browser console itself instead of changing code again and again and debugging via console logs specially when you are dealing with many components integrated together.</p><p>Let’s see how can we achieve that with Angular.</p><p>From Angular 9 and onwards Angular exposes a namespace named <strong>ng</strong> which have some methods to help us debug easily without much hassle and code changes for having console logs. Let’s read what the official documentation have to say about that.</p><blockquote>Exposes a set of functions in the global namespace which are useful for debugging the current state of your application. These functions are exposed via the global ng &quot;namespace&quot; variable automatically when you import from @angular/core and run your application in development mode. These functions are not exposed when the application runs in a production mode.</blockquote><p>The namespace contains following functions :-</p><ol><li><strong>ng.getComponent</strong></li></ol><p>Retrieves the component instance associated with a given DOM element. So in our case for example when we wanted to have component instance of element with id emp-4 and read employee property of it. We can have write following in browser console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7820c5f93359fe0522cbc43f0e13a4b/href">https://medium.com/media/e7820c5f93359fe0522cbc43f0e13a4b/href</a></iframe><p>We can also call any methods inside that component from browser console itself.</p><p><strong>2. ng.applyChanges</strong></p><p>Marks a component for check (in case of OnPush components) and synchronously performs change detection on the application this component belongs to. So, Let’s say we wanted to call applyChanges on your emp4Comp which we just got via getComponent, we can do it like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff91c2c8524cb47fb590cbb6870a0e28/href">https://medium.com/media/ff91c2c8524cb47fb590cbb6870a0e28/href</a></iframe><p><strong>3. ng.getOwningComponent</strong></p><p>Retrieves the component instance whose view contains the DOM element. So, in our case if I call it on emp4Comp it will give me instance of AppComponent and if I call it on a div inside employee component then it will give me instance of EmployeeComponent. It can be used like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37fdfb804bdc5e2a6f48d0e37d6bcba2/href">https://medium.com/media/37fdfb804bdc5e2a6f48d0e37d6bcba2/href</a></iframe><p><strong>4. ng.getContext</strong></p><p>If inside an embedded view (e.g. <strong>*ngIf</strong> or <strong>*ngFor</strong>), retrieves the context of the embedded view that the element is part of. Otherwise retrieves the instance of the component whose view owns the element (in this case, the result is the same as calling <strong>getOwningComponent</strong>).</p><p><strong>5. ng.getDirectives</strong></p><p>Retrieves directive instances associated with a given DOM element. Does not include component instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce78104920488b95905fe8ebeec97292/href">https://medium.com/media/ce78104920488b95905fe8ebeec97292/href</a></iframe><p><strong>6. ng.getHostElement</strong></p><p>Retrieves the host element of a component or directive instance. The host element is the DOM element that matched the selector of the directive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc947f93c488f23c4ac2982efe0b16fb/href">https://medium.com/media/dc947f93c488f23c4ac2982efe0b16fb/href</a></iframe><p><strong>7. ng.getInjector</strong></p><p>Retrieves an <strong>Injector</strong> associated with an element, component or directive instance. It can be used like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6f2d452a16f2aa0c56c2892bf0dab0/href">https://medium.com/media/cf6f2d452a16f2aa0c56c2892bf0dab0/href</a></iframe><p><strong>8. ng.getListeners</strong></p><p>Retrieves a list of event listeners associated with a DOM element. The list does include host listeners, but it does not include event listeners defined outside of the Angular context (e.g. through addEventListener).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d4bf34b9382bc017cc91b636497d84/href">https://medium.com/media/64d4bf34b9382bc017cc91b636497d84/href</a></iframe><p><strong>9. ng.getRootComponents</strong></p><p>Retrieves all root components associated with a DOM element, directive or component instance. Root components are those which have been bootstrapped by Angular.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/659f1eb8e4967aaf6a777f0db36a3ae8/href">https://medium.com/media/659f1eb8e4967aaf6a777f0db36a3ae8/href</a></iframe><blockquote>These are handful of APIs exposed by Angular which can be very useful for debugging in development mode. If used properly, we can debug almost everything from browser console and get access to different parts of our angular applications and use their methods and properties.</blockquote><p>Best of luck for your upcoming bugs and easy debugging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=514e7bff95f6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/debugging-angular-applications-like-a-pro-514e7bff95f6">Debugging Angular Applications Like A Pro</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Router Configuration In Angular]]></title>
            <link>https://blog.devgenius.io/advanced-router-configuration-in-angular-d22c6dc420be?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/d22c6dc420be</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 07:34:22 GMT</pubDate>
            <atom:updated>2020-10-19T07:34:22.510Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6Ncuw6vkV6zHasYp" /><figcaption><strong>Code Image From Unsplash by </strong><a href="https://unsplash.com/@markusspiske"><strong>Markus Spiske</strong></a></figcaption></figure><p>All of us use Routing as part of one or the other application to allow the user to navigate from one page to another via routes. Angular comes with a default solution known as <strong>RouterModule </strong>for implementing Routing in the application.</p><p><strong>RouterModule </strong>is very simple to use and add in your application. In a minimal approach its just a import in modules of your application with the routes you want to have and their respective components. For eg :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a70cb0fc982797691f0d5f83cea64b4/href">https://medium.com/media/7a70cb0fc982797691f0d5f83cea64b4/href</a></iframe><p>So above we used router module in app module imports and gave it a array of routes and now your routes can be used to reach those components considering you have router-outlet tag in app component template. But we also see use of <strong>forRoot </strong>method, So let’s the interface of <strong>RouterModule </strong>to see different methods available with <strong>RouterModule</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23efc1b70500fe45088a0a33d41f0fb8/href">https://medium.com/media/23efc1b70500fe45088a0a33d41f0fb8/href</a></iframe><p>So Its only two methods that are available i.e. forRoot and forChild. From the definition we can see that forRoot accepts two parameters i.e. routes and an optional config object and forChild only accepts routes.</p><blockquote>forRoot is generally used in the root module of your application because it registers the providers/directives/router service etc. required by RouterModule.</blockquote><blockquote>forChild is used to define routes for other modules like lazy loaded modules. The only difference is that it doesn’t re-register the router service.</blockquote><p>What we will be discussing here is the second config object in forRoot method. As it allows us to achieve various things via our routes which we might want to use. So lets see its interface first i.e. ExtraOptions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25befabe6747b4feea27369a772315d5/href">https://medium.com/media/25befabe6747b4feea27369a772315d5/href</a></iframe><p>Let’s discuss these one by one.</p><ol><li><strong>enableTracing</strong></li></ol><p>When this flag is true, angular logs all internal navigation events to the console like when router is activated, when navigation started, when navigation did end etc. Its quite useful for debugging while facing issues with routing configuration.</p><p><strong>2. useHash</strong></p><p>This flag helps in a very specific case. So let’s take a scenario, you have a angular application deployed on tomcat server. You have a route in your Angular application i.e. /dashboard. Now you hit <strong>www.abc.com/dashboard</strong> in browser. What happens in this case is that browser go to server and server starts checking for this URL and returns 404 (Not Found) because this URL was not present on server as this was a Angular route. So there are two ways to resolve this i.e :- Configure your server to return index.html in these cases or use the <strong>useHash </strong>strategy.</p><p>What <strong>useHash </strong>does is that your URL will now become <strong>www.abc.com/#/dashboard</strong>. Now when you will hit the URL the browser doesn’t send the URL after that hash and now you will be served <strong>index.html</strong> and then angular will take care of that dashboard route. But configuring a server is a better approach in this case. Because # is also used for <strong>anchorScrolling </strong>which we will cover in next point.</p><p><strong>3. anchorScrolling</strong></p><p>When set to ‘enabled’, scrolls to the anchor element when the URL has a fragment. Anchor scrolling is disabled by default. What that means is when you will now hit dashboard route the page will be moved to focus this anchor tag wherever its location is on your page. You must have came across web pages where all the content is on same page but by URL they take you to specific section. By this technique you can achieve the same in Angular.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/794d07899a52c171a676ca691f864bc6/href">https://medium.com/media/794d07899a52c171a676ca691f864bc6/href</a></iframe><p><strong>4. initialNavigation</strong></p><p>When set to enabled, the initial navigation starts before the root component is created. The bootstrap is blocked until the initial navigation is complete. This value is required for server-side rendering to work. When set to disabled, the initial navigation is not performed. The location listener is set up before the root component gets created.</p><p>In most of applications this will not be required unless due to a complex scenario more control is required over navigation.</p><p><strong>5. errorHandler</strong></p><p>ErrorHandler is one of the class which we implement in our application to handle errors globally. One way is to have one handler and check error type in it and handle it accordingly with whatever behavior you wanted to achieve. But let’s say you wanted a separate error handler for router to only handle router specific error so you can have a implementation class of error handler and pass it to errorHandler property like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2dcd169df0def5c22537ad269ddf8ab/href">https://medium.com/media/d2dcd169df0def5c22537ad269ddf8ab/href</a></iframe><p><strong>6. preloadingStrategy</strong></p><p>Preloading strategy basically helps in configuring a strategy if you want to preload your lazy loaded modules before the user navigates to route. Angular providers two strategies in-built which are <strong>PreloadAllModules </strong>or <strong>NoPreloading </strong>(the default). You can find number of articles for making a custom preloading strategy and pass it to this attribute.</p><p><strong>7. onSameURLNavigation</strong></p><p>Try one thing, try to navigate to same url in your angular application by router.navigate which is currently activated. You will see that angular ignores this and do not reactivate that route. It is because this property have default value as <strong>ignore</strong>, if you pass it value as <strong>reload</strong> then this behavior will change and your route will be reactivated.</p><p><strong>8. scrollPositionRestoration</strong></p><p>Let’s say user was at some scroll position when was on a page then he navigates to other page. Now he presses back button in browser and you want the scroll position to be same where he left. One way is to write code it by yourself. But angular gives us this property to configure the same. It accepts following values.</p><ul><li>‘disabled’- (Default) Does nothing. Scroll position is maintained on navigation.</li><li>‘top’- Sets the scroll position to x = 0, y = 0 on all navigation.</li><li>‘enabled’- Restores the previous scroll position on backward navigation, else sets the position to the anchor if one is provided, or sets the scroll position to [0, 0] (forward navigation). This option will be the default in the future.</li></ul><p>You can also have a custom scroll restoration behavior which you can find in the official documentation.</p><p><strong>9. scrollOffset</strong></p><p>Configures the scroll offset the router will use when scrolling to an element.</p><p>When given a tuple with x and y position value, the router uses that offset each time it scrolls. When given a function, the router invokes the function every time it restores scroll position.</p><p><strong>10. paramsInheritanceStrategy</strong></p><p>Defines how the router merges parameters, data, and resolved data from parent to child routes. By default (‘emptyOnly’), inherits parent parameters only for path-less or component-less routes. Set to ‘always’ to enable unconditional inheritance of parent parameters.</p><p><strong>11. malformedUriErrorHandler</strong></p><p>Let’s say you want to achieve a particular behavior if user enters invalid character sequences in the url which causes encodeURI to fail. Angular have a default behavior to that which is to route to root URL and loose all the parameters. You can pass a function to this property to achieve a custom behavior overriding the default one. That function will receive three arguments i.e.</p><ul><li>URIError - Error thrown when parsing a bad URL.</li><li>UrlSerializer - UrlSerializer that’s configured with the router.</li><li>url - The malformed URL that caused the URIError</li></ul><p>In your function on the basis of these three parameters you can perform various activities to achieve desired behavior.</p><p><strong>12. urlUpdateStrategy</strong></p><p>Defines when the router updates the browser URL. By default (‘deferred’), update after successful navigation. Set to ‘eager’ if prefer to update the URL at the beginning of navigation. Updating the URL early allows you to handle a failure of navigation by showing an error message with the URL that failed.</p><p><strong>13. relativeLinkResolution</strong></p><p>Enables a bug fix that corrects relative link resolution in components with empty paths. Example:</p><p>Let’s say you had this routing configuration :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/319bb3ff165c9ae263add39cb40a8378/href">https://medium.com/media/319bb3ff165c9ae263add39cb40a8378/href</a></iframe><p>Now in your <strong>HomeComponent </strong>template you had following anchor tag</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a284ab59df853c65e01460f07b2342e/href">https://medium.com/media/7a284ab59df853c65e01460f07b2342e/href</a></iframe><p>This will not work as default value of this field is legacy to support backward compatibility. In legacy to make it work you had to use anchor tag like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a99cb6aac0bd31f2241f0f90e6c45c/href">https://medium.com/media/e0a99cb6aac0bd31f2241f0f90e6c45c/href</a></iframe><p>To enable the fix and use it like <strong>./</strong> instead of <strong>../ </strong>you can give this option the value as ‘corrected’ to enable the fix.</p><blockquote>These options allows us to handle most of the common scenarios that we might face in any web application. If we don’t know them we might end up writing a custom implementation which will be like re-inventing the wheel. Hence knowing them is very important and adds one more feather to your hat of expertise in Angular.</blockquote><p>Hope this helps, and wish you achieve more in your application with these options.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d22c6dc420be" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/advanced-router-configuration-in-angular-d22c6dc420be">Advanced Router Configuration In Angular</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Need Of Null Checks Anymore In Typescript]]></title>
            <link>https://blog.devgenius.io/no-need-of-null-checks-anymore-in-typescript-226d1604eea6?source=rss-65e2b418dd54------2</link>
            <guid isPermaLink="false">https://medium.com/p/226d1604eea6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aakash Garg]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 07:14:25 GMT</pubDate>
            <atom:updated>2020-09-22T07:14:25.618Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKTTODerwlj7pEQrQGgVxA.jpeg" /></figure><p>At some point while working with Angular we loved the Safe Navigation aka Elvis Operator (?.) in Angular Templates. As it helps us to forget about having extra null checks while using objects and just use that operator to handle the same for us. Let’s look at a very basic code snippet how this operator is used in Angular Templates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cf7840cf9f61fecbe1e2c7747ddc365/href">https://medium.com/media/6cf7840cf9f61fecbe1e2c7747ddc365/href</a></iframe><p>In the above example, we are using the operator with person object to check for existence of name only if person object is not null. Without this operator there will be an additional requirement of checking that person object is not null.</p><p>This was a exciting feature for developers as it was easy to use and helped to get rid of having null checks everywhere. This operator has been part of many new popular languages like Kotlin. And Many requested for same for Typescript.</p><p>In Typescript although you could achieve it by having something like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67f9edd2ffac8fa0daf87bc9db2cdafa/href">https://medium.com/media/67f9edd2ffac8fa0daf87bc9db2cdafa/href</a></iframe><p>Still it doesn’t feel much nice like use of Elvis operator. And in case of long conditions the code becomes less readable.</p><p>Since typescript is a super set of JavaScript and supports upcoming features of ECMAScript. Typescript from v 3.7 came with the following operator with a feature named as Optional Chaining.</p><p>So lets say you want to assign the user’s name to a property. Earlier it would have been something like :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/104f59734e5c23c83c85c651ae8c878f/href">https://medium.com/media/104f59734e5c23c83c85c651ae8c878f/href</a></iframe><p>But from Typescript v3.7 you can use it simply like :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9841845fb8378a80ad6c7051348774a3/href">https://medium.com/media/9841845fb8378a80ad6c7051348774a3/href</a></iframe><p>And the <strong>validateUser</strong> method which we had above can now be changed as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a2748f8008b7578272efdc277f20477/href">https://medium.com/media/5a2748f8008b7578272efdc277f20477/href</a></iframe><p>You might find yourself using Elvis operator to replace a lot of code that performs nullish checks.</p><p>The same operator can now be used for element access and optional calling as well. Let’s look at their example one by one.</p><ol><li><strong>Element Access</strong></li></ol><p>Let’s say you wanted to access any index of array if array is not undefined so you can now directly have it as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88e9a208e9a2561ac83a3bf2b9947012/href">https://medium.com/media/88e9a208e9a2561ac83a3bf2b9947012/href</a></iframe><p>2. <strong>Optional Call</strong></p><p>Let’s say you have a method that accepts a callback function as a parameter. But that parameter is optional, but if this parameter is present then we want to call that callback function from our method. It can now be done like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0468d9bb643546a870d30ddbfb735ca4/href">https://medium.com/media/0468d9bb643546a870d30ddbfb735ca4/href</a></iframe><p>So now callbackFunc will only be called if its passed to the getValue and we didn’t even perform any null check.</p><blockquote>But as this operator gives us flexibility of not having null checks while accessing properties or while calling methods. It needs to be decided properly where not to use this operator.</blockquote><p>We must be very careful while using it in some situations. For example if let’s say you are performing addition and you are having a method to add age of two users. Let’s say you have code like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fce66fae8d2ee4ba85308fa92c44523/href">https://medium.com/media/6fce66fae8d2ee4ba85308fa92c44523/href</a></iframe><p>Lets say the value of secondUser is undefined, and age of firstUser is 24. The elvis operator will not stop the addition and the output will be <strong>NaN </strong>as there will be addition of 24 and undefined.</p><p>So while using in expressions we need to be careful to avoid unexpected results. But yes in conditional statements or property/method access it really helps to avoid unnecessary null checks.</p><p>Hope you enjoy this new operator and have more robust and null safe code without having unnecessary null checks.</p><p>Kudos to no more errors like :-</p><blockquote>Cannot read property name of undefined</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=226d1604eea6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/no-need-of-null-checks-anymore-in-typescript-226d1604eea6">No Need Of Null Checks Anymore In Typescript</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>