<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Jordi Riera</title>
    <description>The latest articles on Forem by Jordi Riera (@renaisense_).</description>
    <link>https://forem.com/renaisense_</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F755475%2Fa01a02c9-d46f-44a6-a901-054a7b642b6b.png</url>
      <title>Forem: Jordi Riera</title>
      <link>https://forem.com/renaisense_</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/renaisense_"/>
    <language>en</language>
    <item>
      <title>Mastering Angular's Change Detection Strategies for Enhanced Performance</title>
      <dc:creator>Jordi Riera</dc:creator>
      <pubDate>Sun, 02 Apr 2023 22:56:52 +0000</pubDate>
      <link>https://forem.com/renaisense_/mastering-angulars-change-detection-strategies-for-enhanced-performance-5055</link>
      <guid>https://forem.com/renaisense_/mastering-angulars-change-detection-strategies-for-enhanced-performance-5055</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Achieving high-performance in Angular applications often relies on understanding and optimizing change detection. Change detection refers to the process by which Angular monitors and updates the UI to reflect data changes. The default change detection strategy may suffice for many applications, but optimizing it can lead to even better performance.&lt;/p&gt;

&lt;p&gt;In this post, we'll dive deeper into Angular's change detection mechanism and discuss advanced optimization techniques to maximize your application's performance. Buckle up for an exciting trip to deeper parts of Angular change detection!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fah9vj88m5e04natki47g.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fah9vj88m5e04natki47g.jpg" alt="Angular Change Detection"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Picture by &lt;a href="https://unsplash.com/@gabrielvdz?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Gabriel Valdez&lt;/a&gt; at &lt;a href="https://unsplash.com/es/fotos/Q6-n5G2vA78?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Change Detection Optimization Strategies
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Profiling Change Detection Performance
&lt;/h3&gt;

&lt;p&gt;Before optimizing change detection, it's essential to profile your application's performance to identify bottlenecks. Using tools like the &lt;a href="https://chrome.google.com/webstore/detail/angular-devtools/ienfalfjdbdpebioblfackkekamfmbnh" rel="noopener noreferrer"&gt;Angular DevTools&lt;/a&gt; extension for Chrome, you can inspect your component tree and visualize change detection cycles and pinpoint areas that need optimization.&lt;/p&gt;

&lt;h3&gt;
  
  
  Zone.js and Angular's Change Detection
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe23ujtl5y1c8zn0k6x0l.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe23ujtl5y1c8zn0k6x0l.jpg" alt="zone.js"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Photo by &lt;a href="https://www.pexels.com/photo/a-yellow-clear-zone-on-asphalt-11054546/" rel="noopener noreferrer"&gt;Enouch E:&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So... what on earth is Zone,js? Zone.js is a library that intercepts asynchronous tasks and "notifies" Angular when tasks complete. By leveraging Zone.js, Angular can automatically trigger change detection when tasks like user interactions, timers, or HTTP requests finish. Understanding the role of Zone.js can help you fine-tune change detection, making your application more performant.&lt;/p&gt;

&lt;h4&gt;
  
  
  Zone.js Pollution and its Effects
&lt;/h4&gt;

&lt;p&gt;Zone.js is designed to intercept and track all asynchronous operations in an application. However, this can sometimes lead to a phenomenon known as "Zone.js pollution," where unrelated asynchronous tasks trigger unnecessary change detection cycles, negatively impacting performance. By identifying and isolating such tasks, you can minimize the impact of Zone.js pollution on your application.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using NgZone to Control Zone.js Behavior
&lt;/h4&gt;

&lt;p&gt;NgZone is an Angular service that wraps Zone.js, providing a consistent interface for working with Zone.js in Angular applications. By using NgZone's runOutsideAngular() method, you can execute code outside of Angular's change detection mechanism, preventing unnecessary or redundant change detection cycles due to Zone.js pollution.&lt;/p&gt;

&lt;h5&gt;
  
  
  When should I consider this:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Your application includes third-party libraries that use asynchronous tasks, such as analytics, charts or real-time data streaming services. These tasks may cause unnecessary or redundant change detection cycles, degrading performance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Code example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;NgZone&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;ngZone&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;NgZone&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

&lt;span class="c1"&gt;// Running code outside of Angular's change detection&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;ngZone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;runOutsideAngular&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// Your code here&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Improving ChangeDetectionStrategy.&lt;em&gt;OnPush&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0thp56sp8fl955rhi9jv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0thp56sp8fl955rhi9jv.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Photo by &lt;a href="https://unsplash.com/@huntleytography?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Devon Janse van Rensburg&lt;/a&gt; at &lt;a href="https://unsplash.com/es/fotos/tjVImOAspag?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We know that one of the ways to improve performance in a component is using OnPush change detection strategy. We reduce the amount of things that angular needs to keep track of (namely Input changes, events oroginated from the component and observable new emissions in the async pipe, although the last one is technically a &lt;code&gt;markForCheck()&lt;/code&gt; strategy) However, we can improve the performance of the OnPush strategy by following these tips to further optimize your application's performance:&lt;/p&gt;

&lt;h4&gt;
  
  
  1.Debounce Input Changes
&lt;/h4&gt;

&lt;p&gt;If your component receives rapid input changes, debounce the changes to reduce the number of change detection cycles triggered.&lt;/p&gt;

&lt;h5&gt;
  
  
  When should I consider this:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Your application has input components, such as search bars or sliders, that receive rapid input changes and cause excessive change detection cycles.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Code Example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;debounceTime&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs/operators&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Debouncing input changes&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;searchInput&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;valueChanges&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="nf"&gt;debounceTime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2.Optimize Observables
&lt;/h4&gt;

&lt;p&gt;Use operators like &lt;code&gt;distinctUntilChanged()&lt;/code&gt; or &lt;code&gt;shareReplay()&lt;/code&gt; to limit unnecessary emissions and optimize change detection cycles.&lt;/p&gt;

&lt;h5&gt;
  
  
  When should I consider this:
&lt;/h5&gt;

&lt;p&gt;-Your application uses RxJS Observables extensively, and you need to ensure that only necessary emissions trigger change detection cycles. &lt;/p&gt;

&lt;h5&gt;
  
  
  Code Example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;distinctUntilChanged&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;shareReplay&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs/operators&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Using distinctUntilChanged and shareReplay operators&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data$&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;dataService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getData&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="nf"&gt;distinctUntilChanged&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
  &lt;span class="nf"&gt;shareReplay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Other optimization strategies for smoother change detection cycles
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk10a7v1gy7fdomkv2zgt.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk10a7v1gy7fdomkv2zgt.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Photo by &lt;a href="https://www.pexels.com/photo/photo-of-golden-cogwheel-on-black-background-3785932/" rel="noopener noreferrer"&gt;Miguel Á. Padriñán:&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To further optimize change detection performance, consider the following strategies:&lt;/p&gt;

&lt;h4&gt;
  
  
  1. Immutable Data:
&lt;/h4&gt;

&lt;p&gt;By using immutable data structures, you can ensure that data changes only when necessary. This can significantly reduce the number of change detection cycles, as Angular will only need to check for reference changes instead of deep object comparisons.&lt;/p&gt;

&lt;h5&gt;
  
  
  When should I consider this:
&lt;/h5&gt;

&lt;p&gt;-Your application uses large data objects that frequently change, causing performance issues due to excessive deep object comparisons during change detection cycles.&lt;/p&gt;

&lt;h5&gt;
  
  
  Code Example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;List&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;immutable&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Mutable array of objects&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;mutableData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Item 1&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Item 2&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Item 3&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// Converting mutable data to an immutable List of objects&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;immutableData&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;mutableData&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Immutable data:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;immutableData&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Updating an item in the immutable data (returns a new List)&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;updatedImmutableData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;immutableData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;immutableData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Updated Item 2&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Updated immutable data:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;updatedImmutableData&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2.Batch Updates:
&lt;/h4&gt;

&lt;p&gt;Accumulate multiple data changes before updating the UI, reducing the frequency of change detection cycles. This can be done by using techniques like debouncing or throttling.&lt;/p&gt;

&lt;h4&gt;
  
  
  3.Using ChangeDetectorRef:
&lt;/h4&gt;

&lt;p&gt;The ChangeDetectorRef service allows you to manually mark components as needing change detection. This can be useful when working with asynchronous tasks that are not automatically tracked by Zone.js, or when using third-party libraries that operate outside Angular's change detection mechanism.&lt;/p&gt;

&lt;h5&gt;
  
  
  When should I consider this:
&lt;/h5&gt;

&lt;p&gt;-Your application integrates with third-party libraries that operate outside Angular's change detection mechanism, and you need to ensure that the UI updates when the data changes.&lt;/p&gt;

&lt;h5&gt;
  
  
  Code Example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;ChangeDetectorRef&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;cd&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ChangeDetectorRef&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

&lt;span class="c1"&gt;// Triggering change detection manually&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;detectChanges&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="o"&gt;----&lt;/span&gt;
&lt;span class="c1"&gt;// Marking a component for check&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;markForCheck&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  4.Utilize TrackBy with *ngFor
&lt;/h4&gt;

&lt;p&gt;When using *ngFor with OnPush, use the trackBy function to minimize DOM manipulation and improve performance.&lt;/p&gt;

&lt;h5&gt;
  
  
  When should I consider this:
&lt;/h5&gt;

&lt;p&gt;-Your application uses *ngFor to render large lists, and you need to minimize DOM manipulation to improve performance.&lt;/p&gt;

&lt;h5&gt;
  
  
  Code Example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Component&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Component&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;selector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;app-list&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;template&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;`
    &amp;lt;ul&amp;gt;
      &amp;lt;li *ngFor="let item of items; trackBy: trackById"&amp;gt;{{item.id}} - {{item.name}}&amp;lt;/li&amp;gt;
    &amp;lt;/ul&amp;gt;
  `&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ListComponent&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Item 1&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Item 2&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
  &lt;span class="p"&gt;];&lt;/span&gt;

  &lt;span class="nf"&gt;trackById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;index&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;any&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion:
&lt;/h2&gt;

&lt;p&gt;Mastering Angular's change detection strategies is vital for building high-performance applications. By understanding the intricacies of Angular's change detection mechanism and implementing advanced optimization techniques, you can significantly enhance your application's performance. &lt;/p&gt;

&lt;p&gt;Finally if you have any questions or suggestions feel free to show up and comment! &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>angular</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Angular Dependency Injection Understood III</title>
      <dc:creator>Jordi Riera</dc:creator>
      <pubDate>Mon, 14 Nov 2022 19:25:19 +0000</pubDate>
      <link>https://forem.com/renaisense_/angular-dependency-injection-understood-iii-4a20</link>
      <guid>https://forem.com/renaisense_/angular-dependency-injection-understood-iii-4a20</guid>
      <description>&lt;p&gt;In the last chapter we learned how angular determines who is responsible to provide our dependencies. Today we will explore how once the provider has been determined we can choose what and how we provide our dependencies.&lt;/p&gt;

&lt;p&gt;By default when we define a provider token we use the syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers:[Service]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This in fact is a shorthand version for the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers:[{provide: Service, useClass: Service}]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So what is this provider configuration object? And what properties does it take?&lt;/p&gt;

&lt;p&gt;Angular gives us the option to define how we provide our Service.&lt;br&gt;
There are 4 provider definition objects that tell the provider how to create our Service.&lt;/p&gt;

&lt;p&gt;Let's review them one by one and when to use them.&lt;br&gt;
We'll begin with the default one:&lt;/p&gt;
&lt;h3&gt;
  
  
  useClass
&lt;/h3&gt;

&lt;p&gt;With this definition we can choose a specific class to be used as the base to instantiate our service. Taking advantage of the different scopes of the injectors we can use different classes to instantiate the service depending on where we are providing the dependency. &lt;/p&gt;

&lt;p&gt;for instance we could do:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--P3qXyFeN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aym7pbtx6xyqyk54zjuk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--P3qXyFeN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aym7pbtx6xyqyk54zjuk.png" alt="useClass" width="880" height="381"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In what cases would this be useful? &lt;/p&gt;

&lt;p&gt;Let's imagine we are creating a generic MatStepper and we want a different action on the click of the final step depending on which component or module is using that generic stepper. We can provide a StepperService on the component but use a different class to actually implement it so the actions would be different even if we are calling the same service and same method&lt;/p&gt;

&lt;p&gt;Another useful case is during testing, sometimes we want a simpler implementation of our service while doing unit tests. In our testbed we can provide the same dependency using a simpler class that satisfies our needs in that test&lt;/p&gt;
&lt;h3&gt;
  
  
  useExisting
&lt;/h3&gt;

&lt;p&gt;This is somewhat the opposite of useClass. Instead of mapping one token to different classes we are mapping different tokens to the same class. In some way is like using different aliases for the same class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers:[NewLogger,{provide:OldLogger, useExisting:NewLogger}]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example wherever we are injecting the OldLogger we will be using the already existing instance of NewLogger. &lt;/p&gt;

&lt;p&gt;This approach can be helpful if we want to replace a legacy service with a new one, whenever replacing the implementations of the legacy service can be too costly.&lt;br&gt;
If in this case we used useClass, we would create two different instances of the same NewLogger&lt;/p&gt;

&lt;h3&gt;
  
  
  useFactory
&lt;/h3&gt;

&lt;p&gt;There might be some cases where we can't know before hand which implementation of our service should be instanced, because it might be dependent on runtime conditions. &lt;/p&gt;

&lt;p&gt;For these cases angular gives us the option to pass a function that will create the service during runtime using parameters known at that moment by the application. This function is called a service factory (hence useFactory)&lt;/p&gt;

&lt;p&gt;A typical use case might be that we want to instantiate a service via one class or another depending of user permissions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nlqAsxH3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q826hcah3jco56f84oya.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nlqAsxH3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q826hcah3jco56f84oya.png" alt="useFactory" width="880" height="584"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is important to add the deps property when the factory function has other dependencies itself, in this case the LoggerServiceFactory depends on the UserService, so we added it in the deps in its provider object&lt;/p&gt;

&lt;h3&gt;
  
  
  useValue
&lt;/h3&gt;

&lt;p&gt;When we want to provide constants or configuration parameters in the DI we can use useValue to assign static values to our providers&lt;/p&gt;

&lt;p&gt;We'll get more in detail with useValue in the next chapter when we explore what injectionTokens are.&lt;/p&gt;

&lt;p&gt;For now we have seen 3 very useful modifiers for our providers and common cases where they might be applicable.&lt;/p&gt;

&lt;p&gt;As usual any questions you may have I'll be glad to answer and feel free to follow me to get more updates on my articles.&lt;/p&gt;

&lt;p&gt;Thanks!&lt;/p&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Angular content projection and SOLID code (ng-content)</title>
      <dc:creator>Jordi Riera</dc:creator>
      <pubDate>Tue, 01 Nov 2022 18:46:22 +0000</pubDate>
      <link>https://forem.com/renaisense_/angular-content-projection-and-solid-code-ng-content-5940</link>
      <guid>https://forem.com/renaisense_/angular-content-projection-and-solid-code-ng-content-5940</guid>
      <description>&lt;p&gt;I remember the first time I was told what content projection was and in particular what ng-content did, my first reaction was: "This makes little sense, why would I waste time resorting to these 'juggler tricks' when I can do the same without these"&lt;/p&gt;

&lt;p&gt;But the truth is that content projection is an easy to grasp concept that can help you write better code and follow SOLID principles while developing in angular.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is content projection
&lt;/h3&gt;

&lt;p&gt;Content projection in angular is the possibility to take whatever is between a component's tags and have that content show inside the very same component.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z0xKuvaA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8w5hjdfo1o1we3jngcw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z0xKuvaA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8w5hjdfo1o1we3jngcw.png" alt="ng-content explanation" width="880" height="563"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I know what you are thinking, why bother doing it this way when you can do it manually without much effort. &lt;br&gt;
To illustrate the advantages of content projection I'll use one application that uses a card to display some diverse information inside of it.&lt;/p&gt;

&lt;p&gt;On the first component I will use an approach without content projection. On the other I will use content projection&lt;/p&gt;

&lt;h3&gt;
  
  
  Absence of content projection
&lt;/h3&gt;

&lt;p&gt;Normally without content projection we could use an approach similar to this one:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--atVYJG5Z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtas38j91ydhyst8zz3l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--atVYJG5Z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtas38j91ydhyst8zz3l.png" alt="Card with ngIf" width="880" height="605"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We use ngIf to determine what content gets displayed depending on an input property value, and if it needs to escalate we would use ngSwitch for each and every option that was necessary to display.&lt;/p&gt;

&lt;p&gt;This approach has short legs because sooner or later the component gets packed with ngSwitch/Cases and loses readability. &lt;/p&gt;

&lt;p&gt;But not only that, if later on the specifications change and the card needs new sections or different looks you are modifying the same component, which now probably holds a few more lines of code due to the different ngSwitch so the maintainability of the code suffers.&lt;/p&gt;

&lt;p&gt;This would trigger in my mind a warning of potential &lt;a href="https://en.wikipedia.org/wiki/Single-responsibility_principle"&gt;single responsibility&lt;/a&gt; principle failure. We are mixing the Card UI display with the content choices responsibility.&lt;br&gt;
Also with this approach if we need to extend the functionality of this component with different content options we are forced to modify its source code, so we are breaking the &lt;a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle"&gt;open-closed &lt;/a&gt;SOLID principle&lt;/p&gt;

&lt;h3&gt;
  
  
  With content projection
&lt;/h3&gt;

&lt;p&gt;Using angular content projection the approach to follow would be something on these lines:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3lZnjLYs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/liurqzk4po9qdsbw80hq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3lZnjLYs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/liurqzk4po9qdsbw80hq.png" alt="Using ng-content" width="880" height="563"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and used in the following way:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5tzlsHIH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/leh497e2fhbl1zfcrdq8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5tzlsHIH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/leh497e2fhbl1zfcrdq8.png" alt="ng-content usage " width="880" height="473"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So we have one simple generic card component that only cares about how the card looks and behaves, and we have separate components or elements in charge of the content and their implementations do not interfere&lt;/p&gt;

&lt;p&gt;If we compare this approach to the previous one, I think the advantages start to become obvious. The separation of concerns between the card UI and its contents is clear and well defined and any extension of contents doesn't imply changing the card component itself. And the same the other way around, the need to adjust how the card UI looks and acts does not interfere in the definition and implementation of its contents.&lt;/p&gt;

&lt;p&gt;This way we have a code that is clearer to maintain and less error prone due to the modularity of the concepts and responsibilities, plus we increase the reusability of our code in a great deal&lt;/p&gt;

&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;With content projection we can achieve a greater modularity of our code and increased reusability since we can create generic components that can be extended as needed throughout our application without the need to modify their source code.&lt;/p&gt;

&lt;p&gt;Also this complies with two SOLID principles:&lt;br&gt;
Open-closed principle and Single responsibility principle&lt;/p&gt;

&lt;p&gt;So all in all this easy to learn angular feature can help us in our everyday code and be better programmers &lt;/p&gt;

&lt;p&gt;Also if you want to check out this application I have a basic implementation of this on &lt;a href="https://stackblitz.com/edit/angular-ivy-swxgux?file=src/app/app.component.html"&gt;Stackblitz&lt;/a&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Angular Dependency Injection Understood II</title>
      <dc:creator>Jordi Riera</dc:creator>
      <pubDate>Tue, 25 Oct 2022 15:56:05 +0000</pubDate>
      <link>https://forem.com/renaisense_/angular-dependency-injection-understood-ii-2bbi</link>
      <guid>https://forem.com/renaisense_/angular-dependency-injection-understood-ii-2bbi</guid>
      <description>&lt;p&gt;So in the first chapter of the series we had a general look at what dependency injection is, how it works and why we use it.&lt;br&gt;
We mentioned that there were 3 elements in the pattern: Client, Service and Injector. &lt;/p&gt;

&lt;p&gt;In today's chapter I will talk about the Injectors and their role in dependency injection in angular. So let's get started!&lt;/p&gt;
&lt;h2&gt;
  
  
  Angular Injector:
&lt;/h2&gt;

&lt;p&gt;I am sure that if you have used dependency injection in angular you have seen the following patterns:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ST-cJzdE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5kw3kiih0400efr2sso9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ST-cJzdE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5kw3kiih0400efr2sso9.png" alt="ModuleInjector" width="880" height="313"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Iwxk-SK6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f60wos9o1yr0e64ap5sr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Iwxk-SK6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f60wos9o1yr0e64ap5sr.png" alt="ElementInjector" width="880" height="649"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But when should we use on or the other?&lt;br&gt;
In order to understand when and why to use one or the other we need to explore two important concepts:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Injector Hierarchy&lt;/li&gt;
&lt;li&gt;Dependency resolution&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Injector Hierarchy
&lt;/h3&gt;

&lt;p&gt;Angular has two main injector hierarchies that govern which injector is the responsible to provide the dependency to the requesting Client&lt;br&gt;
These hierarchies are the ModuleInjector and the ElementInjector&lt;/p&gt;
&lt;h4&gt;
  
  
  ElementInjector
&lt;/h4&gt;

&lt;p&gt;When we provide a dependency using the &lt;code&gt;@Component()&lt;/code&gt; or &lt;code&gt;@Directive()&lt;/code&gt; providers we are making that dependency available for that component or directive and all its children (example 2 above) and we are inside the ElementInjector hierarchy.&lt;br&gt;
It's interesting to note that for each component instance that holds that provider definition we are creating a new instance of the dependency&lt;/p&gt;
&lt;h4&gt;
  
  
  ModuleInjector
&lt;/h4&gt;

&lt;p&gt;Whenever we provide the dependency inside the &lt;code&gt;@Injectable()&lt;/code&gt; decorator. (example 1 above) or inside an NgModule's Providers array we are inside the ModuleInjector hierarchy.&lt;br&gt;
In ModuleInjector the hierarchy is not dependant on any children rather it is a quite well defined hierarchy composed of three injectors:&lt;/p&gt;

&lt;p&gt;1 &lt;code&gt;root&lt;/code&gt; ModuleInjector&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable({providedIn:'root'})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2 &lt;code&gt;platform&lt;/code&gt; ModuleInjector&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable({providedIn:'platform'})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3 NullInjector&lt;/p&gt;

&lt;p&gt;And finally, when is the NullInjector reached and what does it do? In this case the answer is quite simple, when angular doesn't find the provider for a dependency anywhere it will reach the NullInjector which is the responsible to throw the&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;NullInjectorError: No provider for dependency 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this takes us to dependency resolution and how does angular traverse the different injectors and determines which Injector should be responsible to provide the dependency&lt;/p&gt;

&lt;h3&gt;
  
  
  Dependency Resolution
&lt;/h3&gt;

&lt;p&gt;According to angular official documentation angular determines how to resolve a dependency the following way:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Against its parents in the ElementInjector hierarchy.&lt;/li&gt;
&lt;li&gt;Against its parents in the ModuleInjector hierarchy.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But what does that actually mean? &lt;br&gt;
What angular does when a dependency is injected in a component or directive is try to search firstly inside its ElementInjector, that is in its own providers and its ancestor components providers.&lt;br&gt;
Only then if angular can not find any provider in the ElementInjector, it starts looking in its ModuleInjector going to the root and then the platform injectors and finally reaching the NullInjector which will throw the error we see when we forget to define a provider for our dependency&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VPfRc_0p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1pbk38ual9rhbb0qtzu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VPfRc_0p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1pbk38ual9rhbb0qtzu.png" alt="dependency resolution flow" width="781" height="856"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So this is the default way angular resolves dependencies, there are some other concepts here but we will see them in another chapter of this series &lt;/p&gt;

&lt;h3&gt;
  
  
  Summing up
&lt;/h3&gt;

&lt;p&gt;So we have seen that we have two main injector hierarchies in angular:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;ElementInjector&lt;/li&gt;
&lt;li&gt;ModuleInjector&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And we have seen how we can provide in one or the other hierarchy of Injectors&lt;br&gt;
We have also learned that angular will traverse all the ElementInjector hierarchy before moving on to the ModuleInjector hierarchy which will end in the NullInjector if no provider is found.&lt;/p&gt;

&lt;p&gt;I hope this helps to clarify when we should provide our dependencies in one way or another and the differences and advantages we can get from it.&lt;br&gt;
If you have any questions regarding this, I will do my best to provide an answer to them.&lt;/p&gt;

&lt;p&gt;See you on the next chapter!&lt;/p&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Angular Dependency Injection Understood I - No needles involved, no worries</title>
      <dc:creator>Jordi Riera</dc:creator>
      <pubDate>Sun, 16 Oct 2022 17:27:46 +0000</pubDate>
      <link>https://forem.com/renaisense_/angular-dependency-injection-understood-i-no-needles-involved-no-worries-4c5h</link>
      <guid>https://forem.com/renaisense_/angular-dependency-injection-understood-i-no-needles-involved-no-worries-4c5h</guid>
      <description>&lt;p&gt;Understanding what dependency injection is outside of angular (DI onwards in the article)  will help us gain a broader perspective of how it works and provide us knowledge on why it is important and how to leverage it inside angular, so the first question is:&lt;/p&gt;

&lt;h3&gt;
  
  
  What is dependency injection?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;DI&lt;/strong&gt; is in fact a programming design pattern in object oriented languages that allows classes to use dependencies without needing to know anything about them. It aims at a greater separation of concerns, decoupling the link between client class and the dependency.&lt;/p&gt;

&lt;p&gt;For instance, normally in an OOP language such as Typescript one would pass dependencies the following way:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2HG_QfUT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2k15que0t1ci81v00mrq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2HG_QfUT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2k15que0t1ci81v00mrq.png" alt="Instantiate new Object" width="880" height="403"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;b&gt;Traditional dependency instantiation&lt;/b&gt;



&lt;p&gt;Basically the class (client) would need to instantiate the new object (service) with the keyword &lt;strong&gt;&lt;em&gt;new&lt;/em&gt;&lt;/strong&gt; with all the properties the new object constructor would need, so the service is hard coded inside the client, creating a tighter coupling between the two classes.&lt;/p&gt;

&lt;p&gt;However using &lt;strong&gt;DI&lt;/strong&gt; the dependency the client does not build the service itself, it only needs to declare the interfaces of the services it uses&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HWt_P69z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6c0hhjxgutwg842vqs7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HWt_P69z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6c0hhjxgutwg842vqs7.png" alt="Dependency Injection Constructor" width="880" height="618"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;b&gt;Dependency Injection&lt;/b&gt;



&lt;h4&gt;
  
  
  Enter the Injector
&lt;/h4&gt;

&lt;p&gt;The heavy lifting in DI is done by an object called injector who is the responsible to provide the new object to the receiving class and keep track of the object graph and each objects implementations.&lt;/p&gt;

&lt;p&gt;This pattern allows for greater modularity and code reusability since each class worries only of itself and not so much about how its dependencies are constructed &lt;/p&gt;

&lt;h4&gt;
  
  
  What about angular?
&lt;/h4&gt;

&lt;p&gt;Since we know that in angular we aim to create code that is very reusable and modular it makes total sense that the angular team opted in for this design pattern as it supports this vision of modular and reusable components code.&lt;/p&gt;

&lt;p&gt;Angular also uses injectors to provide the dependencies, actually the &lt;code&gt;providedIn:'root'&lt;/code&gt; that we normally see in services is referencing to the root injector, which takes care of dependencies that need to be available in the whole application.&lt;/p&gt;

&lt;p&gt;We'll see more about that in the next chapters of this series about dependency injection. For now a small recap:&lt;/p&gt;

&lt;h4&gt;
  
  
  Takeaways
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Dependency injection is a design pattern that aims to have greater code reusability and modularity&lt;/li&gt;
&lt;li&gt;There are 3 main actors in this design: Client, Service and Injector&lt;/li&gt;
&lt;li&gt;The design fits perfectly in angular where client, service and injector are integrated within the framework in order to enhance the modularisation and reusability of its elements (services, components, directives and pipes)&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
