<?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 Kateb Fedi on Medium]]></title>
        <description><![CDATA[Stories by Kateb Fedi on Medium]]></description>
        <link>https://medium.com/@kateb.fedy?source=rss-e6f6b2af8263------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Wuqftbegd3v10FoJ-q_Spg.jpeg</url>
            <title>Stories by Kateb Fedi on Medium</title>
            <link>https://medium.com/@kateb.fedy?source=rss-e6f6b2af8263------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:10:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kateb.fedy/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[Angular Best Practices to adapt]]></title>
            <link>https://medium.com/@kateb.fedy/angular-best-practices-to-adapt-4c7687b16c85?source=rss-e6f6b2af8263------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7687b16c85</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Kateb Fedi]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 13:04:35 GMT</pubDate>
            <atom:updated>2023-02-16T13:04:35.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*wfBTBDe_EK3BVRTt.png" /></figure><blockquote>Angular is a TypeScript-based, free and open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS. Angular is the most powerful framework for building dynamic programming structures. The main building blocks of Angular are modules, components, metadata, templates, data binding, services, directives, and dependency injection. It has a wide spectrum of other internal platforms for designing single-page applications using HTML, CSS, and Typescript. By using Angular technology, we can create more compatible and robust UI applications. Because of these functionalities, Angular is still one of the most popular front-end frameworks in 2023.</blockquote><p>This article aims to highlight the best practices from Angular that would ensure optimal implementation by using the Angular project for better performance.</p><h3>1. Use Angular CLI</h3><p>The Angular CLI also abbreviated as Angular Command Line Interface is an end-to-end tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell. CLI simplifies your overall process and is able to quickly record schedules as well. So, when you are using CLI for your Angular applications, you must know the basic functions of Angular CLI.</p><p>1- npm install -g <a href="http://twitter.com/angular/cli">@angular/cli</a> : install CLI using npm packages <br>2- ng new : create an app that already works, out of the box.<br>3- ng generate : used for generating components, services, routes and pipes with test shells.<br>4- ng serve : helps to test your app locally when developing.<br>5- ng test : for running various Angular tests on your app.<br>6- ng lint : helps your Angular code shine.</p><h3>2. Use Features of ES6</h3><p>ES6 stands for ECMAScript 6 which provides new syntax and features to make code that is more modern and more clear. It is continuously modernized with new functionalities and features. ES6 features like Let and Const, Arrow Functions, Object Literals string interpolation makes JavaScript programming easier.</p><h3>3. Use Lazy Loading</h3><p>Big applications contain a lot of routes. It’s a good practice to use lazy loading to load the module for a route that’s actually needed, not for all of them. It’s just one line in the code called <strong><em>loadChildren</em></strong>:</p><pre>...<br> {<br>    path: &#39;home&#39;,<br>    loadChildren: () =&gt;<br>      import(&#39;./home/home.module&#39;).then(<br>        (m) =&gt; m.HomeModule<br>      ),<br> }</pre><h3>4. Use trackBy along with ngFor</h3><p>Using only *ngFor directive without trackBy function in an angular application will remove all the DOM elements and then it will recreate the DOM elements again in the DOM tree. So even when the same data is getting used, it’ll slow the application performance when there is a lot of data. That is why it is good to use trackBy along with *ngFor directive.</p><p>In component.ts file:</p><pre>...<br>trackByItemCode(index: number, item: any): string {<br>return item.code;<br>}</pre><p>In component.html file:</p><pre>&lt;div *ngFor=&#39;let item of items; trackBy:trackByItemCode&#39;&gt;<br>{{ item }}<br>&lt;/div&gt;</pre><h3>5. Avoid ‘any’ type</h3><p>Avoiding the use of ‘any’ type can potentially lower the number of unexpected issues. Also, not using any type in our application will make the refactoring uncomplicated. The problems can be restricted by typing the specific variables and keeping others away.</p><h3>6. Use Lint Rules</h3><p>The tslint has various inbuilt options like no-any, no-console, no-magic-numbers, etc, which can be configured in tslint.json file. It enforces the program to be decent and more consistent. It can be customized with your own lint rules and configurations. This ensures the readability and consistency of our code.</p><h3>7. Prevent Memory Leaks</h3><p>When we navigate from one component to the other component, the first component is destroyed and the other component initializes. The first component was subscribed to the Observable and now the component is destroyed. This can cause memory leaks.</p><p>We can prevent by following tips,</p><h4>* Using takeUntil()</h4><p>TakeUntil keeps a check on second Observables and once the value of observables is generated then it will dispose of the subscription and the cycle gets finished.</p><pre>this.itemService.GetListItem()<br>      .pipe(takeUntil(this.ngUnsubscribe))<br>      .subscribe(res =&gt; {this.itemList = res;});<br><br><br>ngOnDestroy() {<br>  this.ngUnsubscribe.next();<br>  this.ngUnsubscribe.complete();<br>}</pre><h4>* Using the Async pipe</h4><p>It subscribes to an Observable or Promise and returns to the recent emitted value.</p><pre>&lt;div *ngFor=&quot;let item of itemService.GetItemList() | async&quot;&gt;<br>{{item.name}}<br>&lt;/div&gt;</pre><h4>* Using take(1)</h4><p>It makes sure that you’re getting the data only once.</p><pre>this.itemService.GetItemList()<br>      .pipe(take(1))<br>      .subscribe(res = {this.itemList = res;})</pre><h3>8. Avoid Logic in templates</h3><p>Even when the function calls in angular templates that are technically correct, all template related business logic can be extracted into a component. It assists in unit testing and also reduces bugs in case of a template change in the future.</p><h3>9. Cache API calls</h3><p>Caching API calls improves performance and saves memory by limiting server requests to fetch redundant information. Some API responses may not change frequently so we can put some caching mechanism and can store those values from the API. When the same API request is made, we can get a response from the cache. Thus, it speeds up the application and also makes sure that we are not downloading the same information frequently.</p><h3>10. Declare Safe Data Types</h3><p>You will initially have to start by confirming the types of data and the set of values that it holds. After that only the possible values will be accepted by the variable. Instead of declaring a variable of a particular type, we can declare it as a list of possible values or a different type.</p><p>Example:</p><pre>type WeekEnd = &quot;Saturday&quot; | &quot;Sunday&quot;;<br> <br>const day1: WeekEnd = &quot;Saturday&quot;;<br>const day2: WeekEnd = &quot;Sunday&quot;;<br>const day3: WeekEnd = &quot;Monday&quot;;</pre><h3>11. Avoid having Subscriptions Inside Subscriptions</h3><p>Technically, nested subscriptions works, but it is not the most effective way. In case, you want the value to be reused in more than one observable then you can use preferable chaining options like combineLatest, withLatestFrom, etc rather than subscribing one observable in the subscribe block of another observable.</p><p>Example:</p><pre>observable1$.pipe(<br>   first(1)<br>)<br>.subscribe(res1 = {<br>    observable2$.pipe(<br>        first(1)<br>    )<br>    .subscribe(res2 = {<br>        console.log(`${res1}  ${res2}`);<br>    });<br>});</pre><p>After using withLatestFrom:</p><pre>observable1$.pipe(<br>    withLatestFrom(observable2$),<br>    first()<br>)<br>.subscribe(([res1, res2]) = {<br>    console.log(${res1};  <br>${res2});<br>});</pre><p>After using combineLatest:</p><pre>combineLatest(observable1$, observable2$).subscribe(<br>  ([res1, res2]) = {<br>    console.log(`${res1}  ${res2}`);<br>  }<br>);</pre><h3>12. Follow Consistent Angular Coding Best Practices</h3><p>1- Make sure that the code does not exceed 400 lines limit per file.<br>2- Ensure that the code does not exceed 75 lines for each function.<br>3- If the variables have constant values, declare them with ‘const.’<br>4- Name of properties and methods should be used in lower camel cases.<br>5- Always leave an empty line between imports and modules.</p><h3>13. Build Reusable Components</h3><p>Building reusable components is a golden rule that cannot be omitted when discussing Angular.js best practices. If there is a part of your Angular app’s UI that you know you would need in multiple places, build a component for it and use the component. This will help in implementing the UI element consistently throughout the application. And also, if your app goes through a redesign process for some reason, you will not have to change the UI code at 100s of places. You need to change the component, and you’re good to go.</p><h3>14. Write tests</h3><p>Writing tests may seem like an unnecessary overhead but it’s a vital practice for all developers. Local unit tests and final automated end-to-end tests are <strong>valuable assets to detect bugs early.</strong> Writing tests may take some of your time at first, but it will pay off in the future — for example, when you’ll have to compare old and new functionalities after applying changes.</p><p>So don’t neglect your tests!</p><p>The main benefits of writing tests are:</p><ul><li>Faster development process,</li><li>Reduced number of bugs,</li><li>Enabled Test–Driven Development.</li></ul><h3>15. State Management</h3><p>State management is one of the most difficult aspects of software development. Angular’s state management aids in the management of state transitions by storing the state of any type of data.</p><p>There are many countless state management libraries for Angular present in the market, such as NGRX, NGXS, Akita, and others, all of which have different uses and objectives. Before we implement our application, we can choose the best state management for it.</p><p>Some of the advantages of utilizing state management.</p><p>1- It allows data to be shared between multiple components.<br>2- It allows for centralized state transition control.<br>3- The code will be cleaner and easier to read.<br>4- It’s simple to troubleshoot when something goes wrong.<br>5- There are development tools that are available for tracing and debugging in state management libraries.</p><h3>16. Documentation in Code</h3><p>Documenting code is a good practice. It will assist a new developer in understanding the logic and readability of a project. Documenting each variable and method is a good Angular practice.</p><p>Methods must be defined using multi-line comments that indicate what task the method actually does.</p><pre>/**<br>* This is the get function<br>* @param item is the item parameter<br>* @returns returns a string version of item<br>*/<br>function getItem(item: number): string {<br>return item.toString();<br>}</pre><h3>Summary</h3><p>All these best practices described , they’re the result of the long and hard work of Angular developers . They’ve been proven many times before and are extensively battle-tested.</p><blockquote>Through practice, gently and gradually we can collect ourselves and learn how to be more fully with what we do.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7687b16c85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>