<?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 Hasan Kakeh on Medium]]></title>
        <description><![CDATA[Stories by Hasan Kakeh on Medium]]></description>
        <link>https://medium.com/@Hasan.Kakeh?source=rss-af320f574090------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BGW50PqOszjbFcgGeSDNrg.jpeg</url>
            <title>Stories by Hasan Kakeh on Medium</title>
            <link>https://medium.com/@Hasan.Kakeh?source=rss-af320f574090------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Hasan.Kakeh/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[From Zone.js to Zoneless Angular]]></title>
            <link>https://medium.com/@Hasan.Kakeh/from-zone-js-to-zoneless-angular-a60668c2c821?source=rss-af320f574090------2</link>
            <guid isPermaLink="false">https://medium.com/p/a60668c2c821</guid>
            <category><![CDATA[zoneless]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Hasan Kakeh]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 23:02:14 GMT</pubDate>
            <atom:updated>2026-02-18T23:02:14.087Z</atom:updated>
            <content:encoded><![CDATA[<p>Rethinking change detection in modern Angular</p><figure><img alt="Angular zoneless" src="https://cdn-images-1.medium.com/max/1024/1*LnGfs8C6pX745Hy6MTqMjQ.png" /></figure><p>Angular’s change detection system is powerful, but often misunderstood. As Angular evolves toward signals and zoneless applications, many teams find themselves confused about what actually triggers UI updates — and whether older tools like OnPush are still relevant.</p><p><strong>This article builds a clear mental model for:</strong></p><ul><li>How Angular change detection works</li><li>What Zone.js actually does</li><li>What OnPush really means</li><li>How zoneless Angular changes the game</li><li>Common misconceptions — and how to avoid them</li></ul><h4>What Is Change Detection in Angular?</h4><p><strong>⭕Change Detection</strong> is the fundamental mechanism that synchronizes your application’s data model (TypeScript) with the user interface (DOM).</p><p>Whenever Angular runs change detection, it:</p><ol><li>Walks the component tree</li><li>Re-evaluates template expressions</li><li>Updates the DOM where values changed</li></ol><figure><img alt="zone js with default change detection strategy" src="https://cdn-images-1.medium.com/max/709/1*5rhIhpvLmRsqkvp8eFz-Hg.gif" /><figcaption>zone js and default strategy</figcaption></figure><p>⚠️But wait…. who is really triggering change detection ???🧐</p><h4>How Angular Traditionally Knows <em>When</em> to Run Change Detection?</h4><p>Zone.js intercepts asynchronous browser APIs and notifies Angular whenever an async task completes.</p><blockquote><em>🔊</em>“Something <em>might</em> have changed — better check the UI.”</blockquote><p>Zone.js wraps (monkey-patches):</p><ul><li>Timers (setTimeout, setInterval)</li><li>Promises (then, async/await)</li><li>DOM events (clicks, input, keyboard)</li><li>HTTP requests (XHR, fetch)</li><li>WebSockets, observers, and more</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpZGOBTI4eOxXTBeBUbwnA.png" /></figure><p>This approach is convenient — but expensive.<br>The Cost of Zone.js</p><p>While Zone.js makes Angular easy to use, it introduces problems at scale:</p><ul><li>Change detection runs <strong>more often than necessary</strong></li><li>Async tasks trigger <strong>global checks</strong></li><li>Performance becomes unpredictable</li><li>Developers lose clarity about <em>why</em> the UI updated</li></ul><p>This is one of the reasons Angular introduced:</p><ul><li>ChangeDetectionStrategy.OnPush</li><li>Signals</li><li>Zoneless applications</li></ul><h4>Default Change Detection vs OnPush</h4><p><strong>—🛣️ Default Strategy</strong></p><ul><li>Every change detection run checks <strong>the entire component tree</strong></li><li>Simple mental model</li><li>Poor performance at scale</li></ul><p><strong>—🚩 OnPush Strategy</strong></p><p>OnPush tells Angular:</p><blockquote><em>“Only check this component when there is a </em>clear reason<em> to do so.”</em></blockquote><p>Angular will check an OnPush component only when:</p><ul><li>An input() <strong>reference</strong> changes</li><li>An event originates from the component</li><li>An observable emits via async pipe</li><li>A signal used in the template updates</li><li>Change detection is triggered manually</li></ul><p>OnPush <strong>limits propagation</strong> of change detection.</p><blockquote><em>ℹ️</em>Angular is moving to set onPush as default strategy</blockquote><blockquote><a href="https://github.com/angular/angular/discussions/66779">Setting OnPush as the default Change Detection Strategy</a></blockquote><figure><img alt="zone js with Onpush change detection strategy" src="https://cdn-images-1.medium.com/max/727/1*qCT9Mw7S_mhT6f_DiALNnw.gif" /><figcaption>zone js and onpush strategy</figcaption></figure><h4>What Zoneless Angular Actually Means</h4><p>Zoneless Angular removes <strong>automatic change detection triggers</strong>.</p><p>Without Zone.js:</p><ul><li>Async browser APIs do <strong>not</strong> trigger change detection</li><li>Promises resolving won’t update the UI automatically</li><li>Timers and HTTP responses are ignored by Angular unless explicitly connected to state</li></ul><p>Zoneless Angular answers only one question:</p><blockquote><em>“When should change detection run?”</em></blockquote><p><strong><em>The Big Misunderstanding:</em>🤯</strong></p><h4><strong>— “ Zoneless Removes the Need for OnPush ” —</strong></h4><p>This is <strong>false</strong> — and one of the most common mistakes teams make.</p><p>Why?</p><p>Because <strong>zoneless and </strong><strong>OnPush solve different problems</strong>.</p><p><strong>Separate the Responsibilities</strong></p><p>When change detection runs — — &gt; Zone/Zoneless</p><p>How the view updates — — &gt; Change Detection</p><p>Which components are checked — — &gt; OnPush</p><p>Zoneless removes <strong>implicit triggers</strong>.<br>OnPush removes <strong>implicit propagation</strong>.</p><p>One does not replace the other.</p><p><strong>Why </strong><strong>OnPush Is Still Essential in Zoneless Apps</strong></p><p>Even in zoneless Angular:</p><ul><li>Components still form a tree</li><li>Change detection still walks that tree</li><li>Signals can update frequently</li></ul><p>Without OnPush:</p><ul><li>Updates can still fan out across large subtrees</li><li>Performance becomes unpredictable</li><li>Large apps accumulate hidden cost</li></ul><figure><img alt="Angular Zoneless with mixed strategy (onpush-default) focuses on onpush" src="https://cdn-images-1.medium.com/max/725/1*A6XGIu51Sm_plhyzvqvksQ.gif" /><figcaption>Angular Zoneless with mixed strategy (onpush-default) focuses on onpush</figcaption></figure><figure><img alt="Angular Zoneless with mixed strategy (onpush-default) focuses on default" src="https://cdn-images-1.medium.com/max/729/1*xo_aaR6m-GCKn6EgbQNVBw.gif" /><figcaption>Angular Zoneless with mixed strategy (onpush-default) focuses on default</figcaption></figure><h4>— “ Signals Replace OnPush ” —</h4><p>No.</p><ul><li><strong>🚦Signals</strong> decide <strong>what data changed</strong></li><li><strong>🚩OnPush</strong> decides <strong>which components react</strong></li></ul><p>They work best <strong>together</strong>.</p><h3>Final Takeaways</h3><ul><li>Zone.js wraps async APIs to trigger change detection automatically</li><li>Zoneless Angular removes those automatic triggers</li><li>Change detection still exists in zoneless mode</li><li>OnPush is still critical for performance</li><li>Signals, OnPush, and zoneless are <strong>complementary</strong></li><li>The future of Angular is <strong>explicit, predictable reactivity</strong></li></ul><h4>Resources</h4><ul><li><a href="https://angular.love/the-latest-in-angular-change-detection-zoneless-signals">The Latest in Angular Change Detection — All You Need to Know</a></li><li><a href="https://github.com/angular/angular/discussions/66779">Setting OnPush as the default Change Detection Strategy</a></li><li><a href="https://angular.dev/guide/zoneless">Angular without ZoneJS (Zoneless)</a></li><li><a href="https://github.com/angular/angular/discussions/66779">Setting OnPush as the default Change Detection Strategy</a></li></ul><p>Contact with me:<br>Linked profile: <a href="http://www.linkedin.com/in/hasan-kakeh"><strong>Hasan Kakeh</strong></a><br>Email: <a href="/service/mailto:hasan.kakeh.dev@gmail.com"><strong>hasan.kakeh.dev@gmail.com</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a60668c2c821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Angular Universal (Part 2)]]></title>
            <link>https://medium.com/@Hasan.Kakeh/all-about-angular-universal-part-2-9c5327229696?source=rss-af320f574090------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5327229696</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[angular-universal]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular-ssr]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Hasan Kakeh]]></dc:creator>
            <pubDate>Sat, 23 Dec 2023 18:11:57 GMT</pubDate>
            <atom:updated>2023-12-23T18:16:52.622Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to implement Angular Universal in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3RGEFtnHe9yTwngPR4kPw.png" /></figure><h4>Introduction</h4><p>Welcome back to the second part of our exploration into Angular Universal! In our previous article, we delved into the fundamental aspects of Angular Universal, shedding light on its key concepts and significance. If you missed it, catch up here: <br><a href="https://medium.com/@Hasan.Kakeh/all-about-angular-universal-in-2023-part-1-118b3ec285ef"><strong> All about Angular Universal (Part 1)</strong></a></p><h4><em>Implementation Streamlined with Angular 17 🚀🔥</em></h4><p>implementing Angular Universal has never been smoother, especially with the advancements introduced by the Angular team in version 17. In this section, we’ll guide you through the steps to seamlessly integrate Angular Universal into your project.</p><p>For New Projects: Creating a new Angular project with Server-Side Rendering (SSR) is now as simple as adding a suffix. Just use the following command:</p><pre>ng new my-app --ssr</pre><p>For Existing Projects: If you’re working with an existing project, adding Angular Universal is just a few commands away. Follow these steps based on your Angular version:</p><p>For Angular 17 and Above:</p><pre>ng add @angular/ssr</pre><p>For Older Versions:</p><pre>ng add @nguniversal/express-engine</pre><p>Once you’ve executed these commands, a set of essential files will be generated. Let’s dive into these files to understand their roles in the Angular Universal setup. Let the exploration begin! 🚀✨</p><h4>Exploring Generated Files:🕵️‍♂️</h4><ul><li>( main.server.ts ) <br>When you build an Angular Universal application, you have both a client-side and a server-side application. The main.server.ts file is the entry point for the server-side application.</li><li>( app.config.server.ts ) or ( app.server.module.ts ) for older versions<br>this file is responsible for defining the server-side module that will be used during server-side rendering.<br>Import the necessary Angular modules and dependencies. These may include the core Angular modules, server-specific modules, and any other modules needed for server-side rendering.</li><li>( server.ts )<br> this is your node server which has functionality that renders the application and gives it to the end user.</li></ul><p>let’s focus on server.ts and get a lock on what it contains,</p><p>I will put some of the comments on the initial file code to explain it,<br> so please be patient 🤓</p><pre>import { APP_BASE_HREF } from &#39;@angular/common&#39;;<br>import { CommonEngine } from &#39;@angular/ssr&#39;;<br>import express from &#39;express&#39;;<br>import { fileURLToPath } from &#39;node:url&#39;;<br>import { dirname, join, resolve } from &#39;node:path&#39;;<br>import bootstrap from &#39;./src/main.server&#39;;<br><br>// The Express app is exported so that it can be used by serverless Functions.<br>export function app(): express.Express {<br>  const server = express();<br><br>/*import.meta.url: This special property <br>in modern JavaScript (ECMAScript modules) provides the full URL<br>of the current module. In this case, it&#39;s the URL of the server.ts file.*/<br>  const serverDistFolder = dirname(fileURLToPath(import.meta.url));<br><br>/* The overall goal of this code is to dynamically determine the<br>absolute path of the server distribution folder,<br>where the server-side rendered files are located.*/<br>  const browserDistFolder = resolve(serverDistFolder, &#39;../browser&#39;);<br>  const indexHtml = join(serverDistFolder, &#39;index.server.html&#39;);<br><br>/*Creates a CommonEngine instance for rendering <br>Angular applications on the server.*/<br>  const commonEngine = new CommonEngine();<br><br>  server.set(&#39;view engine&#39;, &#39;html&#39;);<br>  server.set(&#39;views&#39;, browserDistFolder);<br><br>  // Example Express Rest API endpoints<br>  // server.get(&#39;/api/**&#39;, (req, res) =&gt; { });<br><br>  // Serve static files from /browser Like images, fonts, icons, styles ....<br>  server.get(&#39;*.*&#39;, express.static(browserDistFolder, {<br>    maxAge: &#39;1y&#39;<br>  }));<br><br>  /* All regular routes use the Angular engine<br>this entry point of your app catches user requests for your web app */<br>  server.get(&#39;*&#39;, (req, res, next) =&gt; {<br>    const { protocol, originalUrl, baseUrl, headers } = req;<br><br>    commonEngine<br>      .render({<br>        bootstrap,<br>        documentFilePath: indexHtml,<br>        url: `${protocol}://${headers.host}${originalUrl}`,<br>        publicPath: browserDistFolder,<br>        providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],<br>      })<br>      .then((html) =&gt; res.send(html))<br>      .catch((err) =&gt; next(err));<br>  });<br><br>  return server;<br>}<br>// function wrap app to support serverless.<br>function run(): void {<br>  const port = process.env[&#39;PORT&#39;] || 4000;<br><br>  // Start up the Node server<br>  const server = app();<br>  server.listen(port, () =&gt; {<br>    console.log(`Node Express server listening on http://localhost:${port}`);<br>  });<br>}<br><br>run();</pre><h4>Running the SSR App:</h4><p>in angular 17 and above you don’t need any special command to run ssr mode it will run as default.<br>so just run 😁</p><pre>np serve</pre><p>for older version</p><pre>npm run dev:ssr</pre><h4>Checking SSR Mode in the Browser:</h4><p>To verify the successful implementation of SSR in your app. you can simply open browser and click on (view page source) or ( crtl+u )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1hWn2fhjPnPx0jkMkLhYQ.jpeg" /></figure><p>will be able to see your app content so here I can see &lt;P&gt;SSR App &lt;/P&gt; <br>which is my app content.</p><h4>Essential Tools for SSR:</h4><p>Here are some essential tools for working with SSR in Angular</p><p><strong>1- Platform Detection:</strong><br>you can use conditional statements based on these functions to execute code specifically for the server or browser</p><pre>import { Component, Inject, PLATFORM_ID } from &#39;@angular/core&#39;;<br>import { isPlatformBrowser, isPlatformServer } from &#39;@angular/common&#39;;<br>import { RouterOutlet } from &#39;@angular/router&#39;;<br><br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [RouterOutlet],<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrl: &#39;./app.component.scss&#39;<br>})<br>export class AppComponent {<br>  constructor(@Inject(PLATFORM_ID) private platformId: string) {<br>    if (isPlatformBrowser(this.platformId)) {<br>     //....<br>    }<br>    if (isPlatformServer(this.platformId)) {<br>     //....<br>    }<br>  }<br>}</pre><p><strong>2- Sharing data between server and client app:<br></strong>TransferState is a mechanism in Angular that enables efficient management of the transfer of data between the server and the browser. It ensures that the initial state of the application is consistent on both sides, leading to smoother user experiences and improved performance.</p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Injectable, TransferState, StateKey, makeStateKey } from &#39;@angular/core&#39;;<br>import { Observable, of, tap } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class TransferExampleService {<br>  readonly key: StateKey&lt;number&gt; = makeStateKey&lt;number&gt;(<br>    &#39;USER_DATA&#39;<br>  );<br><br>  constructor(private http: HttpClient, private transferState: TransferState) { }<br><br>  getUser(): Observable&lt;any&gt; {<br>    const user = this.transferState.get(this.key, null);<br>    if (user)<br>      return of(user)<br>    return this.http.get(&#39;YOUR_API&#39;).pipe(tap((res) =&gt; {<br>      this.transferState.set(this.key, res)<br>    }))<br>  }<br></pre><p><strong>3- DOCUMENT injection<br></strong>as you know you can access global var like windows and document but when the app runs on the server there is no access to them.<br>to solve this issue you can<br>use “@Inject(DOCUMENT)” to provide an instance from DOM object</p><pre>  constructor(@Inject(DOCUMENT) private document:Document) <br>  {....  }</pre><h4>Enabling Hydration:</h4><p>By default angular 17 comes with enabled hydration you can see <br>provideClientHydration() in app.config.ts<br>for the previous version you can add provideClientHydration() in app.module provider.</p><h4>Important Note⛔: Be Mindful of Data Duplication during Hydration</h4><blockquote>When using TransferState in Angular Universal for efficient data transfer between server and client, exercise caution during the hydration process. By default, hydration may introduce data duplication, resulting in two sets of the same information — one from the TransferState and another from the hydration system.</blockquote><p>Next will cover how to handle (translation — authentication….)<br>I hope you find this guide useful! Feel free to share your thoughts and let me know if there’s a specific topic you’d like me to cover in the future. Thanks for your time! 🙌</p><p>Resources:<br><a href="https://angular.io/guide/ssr">https://angular.io/guide/ssr</a><br><a href="https://blog.angular-university.io/angular-universal/">https://blog.angular-university.io/angular-universal/</a></p><p>Contact with me:<br>Linked profile: <a href="http://www.linkedin.com/in/hasan-kakeh">Hasan Kakeh</a><br>Email: hasan.kakeh.dev@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5327229696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Worst Practices In Angular]]></title>
            <link>https://medium.com/@Hasan.Kakeh/worst-practices-in-angular-aac6e8cc1a69?source=rss-af320f574090------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac6e8cc1a69</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Hasan Kakeh]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 12:04:06 GMT</pubDate>
            <atom:updated>2023-07-12T16:45:38.870Z</atom:updated>
            <content:encoded><![CDATA[<h4>Common Mistakes to Avoid for Better Code Quality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E43lf1rmjRetdTHsB7wE_Q.png" /></figure><h4><strong>Introduction:</strong></h4><p>Angular is a popular and powerful framework for building web applications, but like any technology, it has its share of bad practices. As a developer, it’s important to be aware of these worst practices so you can avoid them and write code that is maintainable, performant, and scalable.</p><p>In this article, we’ll explore some of the most common worst practices in Angular development and offer solutions and best practices for addressing them.<br>So let’s dive in and learn how to avoid these common mistakes in Angular development</p><h4>Please take your breath and be patient.</h4><h4><strong>1. Don’t clear your subscription:</strong></h4><p>It’s a very common practice which can lead to <strong>memory leak</strong> 🤯🤯</p><pre>constructor(private userService:UserService){}<br><br>onInit(){<br>this.userService.user$.subscribe(user=&gt;{...})<br>}</pre><p>When you subscribe to an Observable in Angular, you are creating a connection between the Observable and the subscriber.<br>The Observable will continue to emit values until you unsubscribe from it, even if the component that subscribed to it is no longer in use.</p><p>To solve this simply use one of this:</p><ul><li>takeUntil()</li><li>take()</li><li>takeUntilDestroy()</li><li>subscription.unsubscribe()</li><li>async Pipe</li></ul><h4><strong>2. Use type “any” in every where</strong></h4><p>When you use the “any” type, you lose the benefits of TypeScript’s strong typing system, which helps catch errors and provides better code completion and documentation. Additionally, using “any” can make your code <strong>more difficult to understand and debug</strong>.</p><pre>/** using any **/<br>user:any<br><br>/** using specifc type **/<br>interface User{<br>id:string;<br>name:string;<br>age:number;<br>}<br>user:User</pre><p>By using specific types, you can ensure that your code is type-safe and easier to understand and maintain. <br>So please use TypeScript not JavaScritp 🙏🙏🙏</p><h4>3. Binding static string as attribute to Html element</h4><p>Sometimes you may need to provide a static value to a Html element in Angular. One way to do this is by binding a static string as an input using the square bracket notation, like this:</p><pre>&lt;input [placeholder]=&quot;&#39;hello&#39;&quot;&gt;</pre><p>While this will work as expected, it can cause <strong>unnecessary performance issues</strong>.<br> When you use square brackets to bind an input, Angular treats the input as a dynamic property that needs to be checked in every change detection cycle. This means that Angular will perform additional work to check the input, even though the value will never change.</p><p>To avoid this issue, you can simply pass the static value as a regular input without using the square bracket notation, like this:</p><pre>&lt;input placeholder=&quot;hello&quot; &gt;</pre><h4>4. Using Hostlistner or EventBinding on “scroll || mousemove…” event</h4><p>It’s important to note that triggering change detection on every event can also lead to <strong>performance issues</strong>, especially if you’re listening to events that fire frequently, such as mousemove or scroll events</p><pre>&lt;div (scroll)=&quot;onscroll()&quot;&gt;....&lt;/div&gt;</pre><p>To fix That you can use the NgZone service to run event listeners outside of Angular&#39;s change detection cycle and manual change detection.</p><pre>/** template **/ <br>&lt;div #el&gt;...&lt;/div&gt;<br><br>/** component **/<br>@ViewChild(&#39;el&#39;,{static:true})el:ElementRef;<br><br>constructor(private zone:NgZone,prviate cdr:ChangeDetectorRef){}<br><br>OnInit(){<br> this.zone.runOutsideAngular(()=&gt;{<br>  fromEvent(this.el.natvieElement,&#39;scroll&#39;).subscribe((e)=&gt;{...<br>    if(...){<br>     ...<br>     this.cdr.detectChange()  <br>     }<br>   })<br> })<br>}</pre><p>Another way to optimize the performance of your application when dealing with event listeners is to use RxAngular, which is a library for reactive programming in Angular that provides several features for optimizing performance. One of the features of RxAngular is zone-patched operators, which allow you to run code outside of Angular&#39;s change detection cycle.</p><p><a href="https://www.rx-angular.io/docs/template">Template | RxAngular</a></p><h4>5. Importing shared module in app module</h4><p>When you import the SharedModule in the AppModule, all of the components, directives, and pipes in the SharedModule are included in the main bundle, even if they&#39;re not used in the AppModule. This can cause the bundle size to increase unnecessarily, which can lead to<strong> longer load times</strong> and <strong>slower performance</strong>.</p><pre>@NgModule(<br>{...<br>imports:[SharedModule,...]<br>})<br>export class AppModule { }</pre><p>Simply fix that by avoid importing it in the AppModule or any nested module inside it. Instead, you should only import the SharedModule in feature modules that need to use its shared components.</p><blockquote><strong>Note</strong>: using standalone components can be a good practice in Angular development</blockquote><h4>6. importing the CoreModule in multiple modules</h4><p>The CoreModule is a module that contains services, providers, and other global configurations that are used throughout your application. It&#39;s typically imported only once in the AppModule and should not be imported in any other modules.<br>If you import the CoreModule in multiple modules, you&#39;re essentially creating multiple instances of the same services and providers, which can lead to unexpected behavior and errors. This can also cause <strong>circular dependencies</strong>, where modules depend on each other in a way that can&#39;t be resolved.</p><p>To avoid this issue, you should only import the CoreModule once in the AppModule. If you need to use the services or providers from the CoreModule in other modules, you can import them directly from the CoreModule without importing the CoreModule itself.</p><h4>7. Using setInterval or RxJS operators like interval and timer</h4><p>setInterval is a JavaScript function that executes a given function at a set interval. Similarly, interval and timer are RxJS operators that emit values at a set interval. While these operators can be useful in some cases, using them in Angular can cause issues because they can <strong>trigger change detection frequently</strong> and <strong>impact performance</strong>.</p><pre>OnInit(){<br>/* JavaScript function*/<br>setInterval(()=&gt;{<br>  ...<br>  },1000)<br>/*Rxjs oprators*/<br>const subscription=interval(1000).subscribe(()=&gt;{...})<br>}</pre><p>Like eventBinding to fix this you need to run you code outside of zone and manual change detection.</p><h4>8. Don’t split your code into multiple component</h4><p>When you don’t split your code into multiple components, you may end up with a large, monolithic component that does too many things. This can make it <strong>harder to maintain and reuse the code</strong>, and can also lead to <strong>performance issues</strong> if the component becomes too complex.</p><p>To avoid this bad practice, you should split your code into multiple components whenever possible. Each component should be designed to handle a specific piece of functionality or user interface element, and should be reusable and maintainable.</p><h4>9.Using default change detection strategy</h4><p>The Default change detection strategy is the most commonly used strategy in Angular, and it works well for most applications. When using the Default strategy, Angular will compare the current values of a component&#39;s inputs and internal state with their previous values, and then update the view if necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*14ql3TAFTiyEkuo6.gif" /><figcaption>default change detection</figcaption></figure><p>While the Default change detection strategy works well for most applications, it can be less performant in certain situations. For example, if a component has many inputs that change frequently, this can trigger unnecessary change detection cycles and <strong>impact the performance</strong> of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*2MhL2sKIaCLqf-3K.gif" /><figcaption>onpush change detection</figcaption></figure><p>The OnPush change detection strategy is a way to optimize change detection by only checking a component&#39;s inputs when they change or when an event is fired. This can help reduce the number of unnecessary change detection cycles and improve the performance of your application.</p><h4>10. Using ShareReplay with all requset</h4><p>shareReplay is an RxJS operator that allows you to share the results of an observable with subscribers, so that they don&#39;t have to re-execute the observable. While shareReplay can be useful for caching and optimizing performance, using it with all requests can cause issues because it can <strong>fill up memory</strong> with cached data.</p><pre>constructor(private listService:ListService){<br>  this.list$=this.listService.getList().pipe(shareReplay())<br>}</pre><p>It’s important to use it correctly to avoid these issues.<br>Here are some best practices to follow:<br>1. Use shareReplay only when necessary<br>2. Use a cache timeout<br>3. Use a limited cache size<br>4. Using refCount to clear the cache when there are no subscriptions on</p><h4>Finally :</h4><p>Remember to be patient with yourself and the framework as you work through challenges and find solutions. Don’t rush through your code or make quick fixes without fully understanding the implications, as this can lead to unexpected bugs and performance issues.</p><p>By taking the time to understand Angular’s best practices and avoiding its worst practices, you can build robust and scalable applications that meet your users’ needs. So take a deep breath, stay calm, and keep learning!”</p><p><strong>Hope you find this useful, please let me know if you have any opinions on that or if you have another bad practice to share with us.</strong></p><p>Useful resources:</p><p><a href="https://www.youtube.com/watch?v=WoCReDUpcVs">https://www.youtube.com/watch?v=WoCReDUpcVs</a><br><a href="https://youtu.be/eJs4EJUOnNE">https://youtu.be/eJs4EJUOnNE</a><br><a href="https://www.youtube.com/watch?v=7duYY9IFIuw">https://youtu.be/eJs4EJUOnNE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac6e8cc1a69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Angular Universal in 2023 (part 1)]]></title>
            <link>https://medium.com/@Hasan.Kakeh/all-about-angular-universal-in-2023-part-1-118b3ec285ef?source=rss-af320f574090------2</link>
            <guid isPermaLink="false">https://medium.com/p/118b3ec285ef</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[angular-universal]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hasan Kakeh]]></dc:creator>
            <pubDate>Tue, 23 May 2023 19:39:52 GMT</pubDate>
            <atom:updated>2023-05-23T19:39:52.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E74hEufsXas-rAEMTYjhhQ.png" /><figcaption>Angular Universal 2023</figcaption></figure><p>In this series, we’ll explore the key concepts and techniques behind Angular Universal, and show you how to implement and apply them in your own Angular applications</p><h4>What is Angular Universal?</h4><blockquote>By default, Angular renders applications only in a <em>browser</em>. Angular Universal allows Angular to render an application on the <em>server</em>, generating <em>static</em> HTML contents, which represents an application state. Once the HTML contents is rendered in a browser, Angular bootstraps an application and reuses the information available in the server-generated HTML.</blockquote><p>That what angular guide says but let’s take deep look about it.</p><h4><strong>Client-Side Render (CSR)</strong></h4><p>First, let’s take a look at the default behavior of Angular, which is called <strong>Client-Side Render (CSR)</strong>. CSR means that when a user opens a web app, they request the server for an HTML page, which will be an empty page. As we know, the page will contain a reference to JavaScript files, so the browser will ask for load , parse, and execute them before the user can view the app, for that it’s called client side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8hoY6rln7bXrJRvxLwIhA.png" /><figcaption>Client Side Render</figcaption></figure><h4>But what is problem with CSR?</h4><ul><li><strong>Slower initial page load times :</strong> With CSR, web applications require more time to load initially because the browser must download and execute the necessary JavaScript code before rendering content.</li><li><strong>Poor search engine optimization (SEO) : </strong>Because CSR relies on JavaScript to render content, search engines may have difficulty indexing the content, potentially reducing the visibility and discoverability of the web application.</li><li><strong>Accessibility issues:</strong> CSR can pose challenges for accessibility since web applications must ensure that their dynamic content is accessible to users with disabilities.</li><li><strong>Low Performance</strong>: Especially on mobile device and low network speed because large bundle size.</li></ul><p>here Angular Universal come to solve that, by two strategy, Server Side Render (SSR) and Prerender.</p><h4>So, What is Server Side Render (SSR)?</h4><p>SSR is a technique used in web development to render the initial HTML of a web application on the server, rather than relying on client-side JavaScript to render content. With SSR, the server generates the initial HTML for the requested page and sends it to the browser, which can then display the HTML to the user. This means the browser will have an HTML page that contains a ready-to-show app, instead of an empty page. SSR can provide a faster and more responsive user experience, particularly on slower networks or devices, as the user does not have to wait for client-side JavaScript to download and execute before seeing content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*fhzrD1WTEfX2ZoEMxIvK8w.png" /><figcaption>Server Side Render (Static HTML)</figcaption></figure><p>As we noticed from the image, the HTML page will be larger than before because it contains elements now.</p><p><strong>— But is that mean we will have a non-interactive app because static html?</strong></p><p>Absolutely No, Why we build a angular app if we want show a static html !!<br>to solve that browser will receive also a javascript bundle this process called <strong>Hydration</strong></p><blockquote><strong>Hydration</strong> involves taking the initial HTML generated by the server and “hydrating” it with client-side JavaScript to provide a fully interactive user experience. This allows the application to provide a faster and more responsive user experience, while also ensuring good search engine discoverability and accessibility.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL_qUzFM9OGr0nOAFB2dEw.png" /><figcaption>Server Side Render (Hydration)</figcaption></figure><p>As we see now HTML is generated by the server and sent to the browser, which then displays it to the user. This HTML may contain some basic content and structure, but it is typically <strong>non-interactive</strong> until client-side JavaScript is downloaded and executed.</p><p>Once the necessary JavaScript files have been downloaded and executed in the background, the application can “hydrate” the initial HTML with the client-side JavaScript, which allows it to provide a<strong> fully interactive</strong> experience for the user. At this point, the application can take over and begin rendering dynamic content and responding to user input.</p><h4>What is new in Server side world in 2023?</h4><p>we have now <strong>non-destructive hydration</strong> which will improves application performance by avoiding extra work to re-create DOM nodes,<br>before that the browser when his finsh from execute javascript he destroy the intial page and re-create new dom (<strong>destructive hydration</strong>),</p><p>but now we have ability to to match existing DOM elements to the applications structure at runtime and reuses DOM nodes when possible.</p><p>This results in a performance improvement that can be measured using <a href="https://web.dev/learn-core-web-vitals/">Core Web Vitals (CWV)</a> statistics, such as reducing the First Input Delay (<a href="https://web.dev/fid/">FID</a>) and Largest Contentful Paint (<a href="https://web.dev/lcp/">LCP</a>), as well as Cumulative Layout Shift (<a href="https://web.dev/cls/">CLS</a>). Improving these numbers also affects things like SEO performance.</p><h4>What is Prerender and what is the deffrence between it and SSR ?</h4><p>Pre-rendering is a rendering technique in which pages can be pre-rendered at build time and sent to the browser as and when it is requested.<br>so prerender provide a html with static content</p><p>the<strong> main deffrence</strong> between prerender and ssr is <strong>Prerender </strong>work in build time so the data will be static at all time that mean the server will always provide same html content but in <strong>SSR </strong>the server will render page in every time use ask for page so data can be change which mean it can provide defferent content.</p><p>I hope you enjoyed and got a clear understanding of it<br>wait for another parts for learn how to implement it and what is coming in future.</p><p>usefull resources</p><p>docs:<br><a href="https://angular.io/guide/universal">https://angular.io/guide/universal</a><br><a href="https://blog.angular-university.io/angular-universal/">https://blog.angular-university.io/angular-universal/</a></p><p>vidoes: <br><a href="https://youtu.be/R-BKadZWYnQ">https://youtu.be/R-BKadZWYnQ</a><br><a href="https://youtu.be/aaCWxZhj6CY">https://youtu.be/aaCWxZhj6CY</a><br><a href="https://youtu.be/RFwjJAZOzOA">https://youtu.be/RFwjJAZOzOA</a><br><a href="https://youtu.be/b6MfRwiPhpo">https://youtu.be/b6MfRwiPhpo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=118b3ec285ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy load embed videos (youtube —  vimeo) in Angular]]></title>
            <link>https://medium.com/@Hasan.Kakeh/lazy-load-embed-videos-youtube-vimeo-in-angular-1973d81fab9d?source=rss-af320f574090------2</link>
            <guid isPermaLink="false">https://medium.com/p/1973d81fab9d</guid>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[vimeo]]></category>
            <category><![CDATA[lighthouse]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[youtube]]></category>
            <dc:creator><![CDATA[Hasan Kakeh]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 19:19:56 GMT</pubDate>
            <atom:updated>2023-04-22T19:19:56.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lazy load embed videos (youtube — vimeo) in Angular</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmClD441TG3N9nWI84a6NQ.png" /></figure><p>Lazy loading is a technique used in web development to defer the loading of non-critical resources, such as images and videos, until they are needed. When it comes to embed YouTube/Vimeo videos, lazy loading can be particularly useful for several reasons:</p><h4><strong>Faster page loading:</strong></h4><p>Embedding videos can significantly slow down the loading time of a webpage, especially if there are multiple videos on the page. With lazy loading, the videos are only loaded when the user scrolls to them, which can significantly improve page loading time and overall user experience.</p><h4><strong>Improved website performance:</strong></h4><p>Loading multiple videos on a page can also put a strain on website performance, especially on slower devices and internet connections. By deferring the loading of videos until they are needed, lazy loading can help improve website performance and reduce the risk of crashes or freezes.</p><h4><strong>Reduced data usage:</strong></h4><p>Videos consume a lot of data, so using lazy loading for embed videos can help reduce the amount of data used by the website. This can be particularly important for users who have limited data plans or slow internet connections.</p><h4><strong>Better SEO:</strong></h4><p>Lazy loading can also have a positive impact on SEO, as faster loading pages and better website performance are factors that search engines consider when ranking websites. By improving these factors, lazy loading can help improve a website’s search engine ranking and visibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*kdKBszyKx16p13dxW3ZeSA.png" /><figcaption>Image by page test speed using iframe before using a package</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*kJXODD7dhZWrUqXYQ-ba0A.png" /><figcaption>Page test speed after using a package</figcaption></figure><p>And for that we decided me and my partner <a href="https://github.com/karim-mamdouh">Eng karim mamdouh</a> create native angular package to provide this state.</p><h3>ngx-video-lite</h3><p>ngx-lite-video is an Angular package that provides lazy loading capabilities for embedded iframes from popular video sharing platforms like YouTube and Vimeo. The package is designed to optimize the loading of embedded videos, improving page load times and reducing data usage.</p><p>The package is built specifically for Angular, utilizing Angular’s onpush change detection strategy for efficient rendering and updating of video components. It also includes features such as customizable lazy loading thresholds and options for controlling video playback and display.</p><h4>how to use it:</h4><p>first add package to your angular project</p><pre>npm i ngx-lite-video</pre><p>then add import to component module</p><p>if you want use youtube componet</p><pre>import { NgxLiteYoutubeModule } from &#39;ngx-lite-video&#39;;<br><br>@NgModule({<br>imports:[NgxLiteYoutubeModule]<br>})</pre><p>or import NgxLiteVimeoModule for vimeo component</p><pre>import { NgxLiteVimeoModule} from &#39;ngx-lite-video&#39;;<br><br>@NgModule({<br>imports:[NgxLiteVimeoModule]<br>})</pre><p>then simply add component to your html</p><pre>&lt;ngx-lite-youtube videoId=&quot;VIDEO_ID&quot;&gt;&lt;/ngx-lite-youtube&gt;</pre><p>or</p><pre>&lt;ngx-lite-vimeo videoId=&quot;VIDEO_ID&quot;&gt;&lt;/ngx-lite-vimeo&gt;</pre><p>don’t forget to replace VIDEO_ID .</p><p>and that is all.</p><p>if you want to know more about it you can read npm package page</p><p><a href="https://www.npmjs.com/package/ngx-lite-video">ngx-lite-video</a></p><p>for see demo visit</p><p><a href="https://karim-mamdouh.github.io/ngx-lite-video/">Ngx Lite Video Demo</a></p><p>hope you enjoyed it :) .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1973d81fab9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular validation (best practice)]]></title>
            <link>https://medium.com/@Hasan.Kakeh/angular-validation-best-practice-f8f9778ce343?source=rss-af320f574090------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8f9778ce343</guid>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Hasan Kakeh]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 23:38:16 GMT</pubDate>
            <atom:updated>2023-04-05T23:48:54.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqNmr0DWEi5fuwQKdWoyyA.png" /></figure><p>It’s easy to work with angular validation either if you use template driven or reactive forms.<br>in this article we will focus on working with reactive form how to avoid legacy code like this:</p><pre>&lt;form [formGroup]=&quot;formGroup&quot;&gt;<br>  &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt;<br>  &lt;input id=&quot;email&quot; type=&quot;email&quot; formControlName=&quot;email&quot;&gt;<br>  &lt;span class=&quot;error&quot; *ngIf=&quot;formGroup.controls[&#39;email&#39;].touched &amp;&amp;<br>   formGroup.controls[&#39;email&#39;].errors[&#39;required&#39;]&quot;&gt;<br>   Email is required<br>  &lt;/span&gt;<br>  &lt;span class=&quot;error&quot; *ngIf=&quot;formGroup.controls[&#39;email&#39;].touched &amp;&amp;<br>   formGroup.controls[&#39;email&#39;].errors[&#39;email&#39;]&quot;&gt;<br>   Please provide valid email<br>  &lt;/span&gt;<br>  &lt;button type=&quot;submit&quot;&gt;submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>in preview example every time need new validation you should add new span item and repeat check condition.</p><p>to avoid this and use more clean code we will create a dumb component called “error-field”</p><pre>ng g c error-field</pre><p>typescript file will be</p><pre>import { FormControl, AbstractControl, FormGroupDirective } from &#39;@angular/forms&#39;;<br>import { Component, Input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;error-field&#39;,<br>  templateUrl: &#39;./error-field.component.html&#39;,<br>  styleUrls: [&#39;./error-field.component.scss&#39;],<br>  host: { style: &#39;color: red;&#39; },<br>})<br>export class ErrorFieldComponent {<br>  @Input() control: FormControl | AbstractControl<br>  @Input() errorMessages: Object<br><br>  constructor(public formDirective:FormGroupDirective){<br>  }<br>}</pre><p>control and errorMessages it’s just input to provide formControl and all error messages and we will inject formDirective in constructor to catch form submitted.</p><p>and but in it’s html</p><pre>&lt;ng-container *ngIf=&quot;control.errors &amp;&amp;(control.touched|| formDirective.submitted)&quot;&gt;<br>  {{errorMessages|validation:control.errors}}<br>&lt;/ng-container&gt;</pre><p>first we checked if error exist and control touched or form submitted to prevent show error immediately.</p><p>and as you noticed we need validation pipe to take all messages as value and control error as arguments</p><pre>ng g p validation</pre><p>pipe simply assign a error message with first control error, we often didn’t need more then one message show in same time.</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;validation&#39;<br>})<br>export class ValidationPipe implements PipeTransform {<br><br>  transform(value: any, errorObj: Object): unknown {<br>    return value[Object.keys(errorObj)[0]];<br>  }<br><br>}</pre><p>Finally, all you have to use it is provide control and messages.</p><pre>&lt;form [formGroup]=&quot;formGroup&quot;&gt;<br>  &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt;<br>  &lt;input id=&quot;email&quot; type=&quot;email&quot; formControlName=&quot;email&quot;&gt;<br>  &lt;error-field [control]=&quot;formGroup.controls[&#39;email&#39;]&quot; [errorMessages]=&quot;validationMessages.email&quot;&gt;<br>  &lt;/error-field&gt;<br>  &lt;button type=&quot;submit&quot;&gt;submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>validation message object should be like this</p><pre> validationMessages = {<br>    email: //key is a control name <br>    { // and this is a validation key and message<br>      required: &#39;Email is required&#39;, <br>      email:&#39;Please provide valid email&#39;<br>    }<br>  }</pre><p>now every time you need new validation just add it to your form control and add a key : value message to validationMessages object .</p><p>Hope you find this usefull.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8f9778ce343" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>