<?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>DEV Community: Houdass Youness</title>
    <description>The latest articles on DEV Community by Houdass Youness (@houdass).</description>
    <link>https://dev.to/houdass</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%2F1019475%2Fd469a0b4-8c54-477d-9ba1-ad7c1003f8b3.png</url>
      <title>DEV Community: Houdass Youness</title>
      <link>https://dev.to/houdass</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/houdass"/>
    <language>en</language>
    <item>
      <title>Embracing Zoneless in Angular: A New Era of Change Detection</title>
      <dc:creator>Houdass Youness</dc:creator>
      <pubDate>Mon, 20 Jan 2025 20:47:02 +0000</pubDate>
      <link>https://dev.to/houdass/embracing-zoneless-in-angular-a-new-era-of-change-detection-53hj</link>
      <guid>https://dev.to/houdass/embracing-zoneless-in-angular-a-new-era-of-change-detection-53hj</guid>
      <description>&lt;p&gt;With the release of Angular version 18 on 22 may 2024, the framework introduces an exciting experimental feature: zoneless Angular apps. This innovation eliminates the reliance on the Zone.js library, offering improved performance, reduced overhead, and a simplified debugging experience. In this article, we’ll explore what zoneless applications entail, the advantages they offer, and how you can experiment with this cutting-edge functionality.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Change Detection in Angular (Pre-Zoneless)
&lt;/h2&gt;

&lt;p&gt;Change detection ensures that the application's DOM stays in sync with the underlying data model in components. Traditionally, Angular has relied on &lt;em&gt;Zone.js&lt;/em&gt; to manage change detection. Here's a quick overview of when change detection occurs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;User Interactions&lt;/strong&gt;: Events like button clicks or typing in an input field.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Asynchronous Operations&lt;/strong&gt;: Actions such as HTTP requests, &lt;code&gt;setTimeout&lt;/code&gt;, &lt;code&gt;setInterval&lt;/code&gt; or &lt;code&gt;Promise&lt;/code&gt; resolutions.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Manual Triggers&lt;/strong&gt;: Invocations like &lt;code&gt;ApplicationRef.tick()&lt;/code&gt; or &lt;code&gt;ChangeDetectorRef.detectChanges()&lt;/code&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Zone.js&lt;/em&gt; achieves this by patching browser APIs (e.g., events or timers) and notifying Angular to start change detection. While this approach works seamlessly, it introduces some overhead and can lead to issues like the infamous &lt;em&gt;ExpressionChangedAfterItHasBeenCheckedError&lt;/em&gt;.  &lt;/p&gt;

&lt;h3&gt;
  
  
  Examples of Change Detection Before Zoneless
&lt;/h3&gt;

&lt;p&gt;Before Angular introduced zoneless change detection, &lt;em&gt;Zone.js&lt;/em&gt; was central to automatically tracking and propagating changes to the UI. The following embedded StackBlitz example demonstrates various scenarios:&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-6h4dwhjs?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Simple property set in an event handler&lt;/strong&gt;: Clicking a button updates a &lt;code&gt;counter&lt;/code&gt; property. Zone.js intercepts the event, schedules a change detection cycle, and the UI reflects the updated value.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Simple property set asynchronously&lt;/strong&gt;: An interval updates a &lt;code&gt;tick&lt;/code&gt; property every second. Zone.js detects the asynchronous operation (&lt;code&gt;setInterval&lt;/code&gt;) and schedules change detection to reflect the updated value in the DOM.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Data retrieved from HTTP and stored in an array&lt;/strong&gt;: Data fetched via an HTTP request is stored in an array, and Angular’s default change detection ensures the view updates automatically without requiring user interaction. This works because &lt;code&gt;HttpClient&lt;/code&gt; operates within Angular's zone, triggering change detection when the response is received. However, if the component uses &lt;code&gt;ChangeDetectionStrategy.OnPush&lt;/code&gt; and the array is mutated directly (e.g., using &lt;code&gt;push&lt;/code&gt;), the view might not update unless the reference changes or change detection is triggered manually.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Data retrieved from HTTP with async pipe&lt;/strong&gt;: Using the &lt;code&gt;AsyncPipe&lt;/code&gt; simplifies observables by automatically subscribing and triggering change detection when new data is emitted, eliminating manual handling.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Data retrieved from HTTP and stored in a signal&lt;/strong&gt;: With signals, introduced in modern Angular, state changes directly notify dependent readers, streamlining updates and making the process independent of Zone.js.  &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These examples showcase how &lt;em&gt;Zone.js&lt;/em&gt; historically handled asynchronous operations and change detection, paving the way for Angular's more efficient, lightweight, and scalable zoneless architecture.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Why Go Zoneless?
&lt;/h2&gt;

&lt;p&gt;Moving away from Zone.js brings several benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;&lt;strong&gt;Simplified Change Detection&lt;/strong&gt;&lt;/em&gt;: Developers no longer need to contend with ExpressionChangedAfterItHasBeenCheckedError and other zone-related quirks.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;&lt;strong&gt;Reduced Overhead&lt;/strong&gt;&lt;/em&gt;: Eliminating zone.js lightens the framework, improving runtime performance.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;&lt;strong&gt;Improved Debugging&lt;/strong&gt;&lt;/em&gt;: Zoneless applications provide better control over change detection, making it easier to pinpoint performance bottlenecks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to Configure a Zoneless Angular Application?
&lt;/h2&gt;

&lt;p&gt;Switching to a zoneless application requires a few configuration changes. Here's a step-by-step guide:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Enable Experimental Zoneless Change Detection
In app.config.ts, add the following provider:
&lt;/li&gt;
&lt;/ol&gt;

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

&lt;/div&gt;



&lt;p&gt;Ensure you remove the &lt;em&gt;provideZoneChangeDetection()&lt;/em&gt; provider if it exists.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Remove &lt;em&gt;zone.js&lt;/em&gt; Imports&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Delete import '&lt;em&gt;zone.js&lt;/em&gt;'; from your application files.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Update angular.json to remove zone.js from the polyfills section:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Uninstall zone.js
Run the following command to remove zone.js from your project:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm uninstall zone.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Testing Change Detection Without &lt;em&gt;Zone.js&lt;/em&gt;
&lt;/h2&gt;

&lt;p&gt;The following example demonstrates how change detection behaves in various scenarios without the use of zone.js.&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-nnlmbxjd?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
In this example, we’ve kept the initial setup and simply removed Zone.js. Now, let's break down each of the five scenarios mentioned in the example, analyzing them case by case without Zone.js:&lt;/p&gt;
&lt;h4&gt;
  
  
  First Case: Simple Property Set in an Event Handler
&lt;/h4&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-fftjvfww?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
As you can observe, it works as before, and the view updates when the "increment" button is clicked.&lt;/p&gt;
&lt;h4&gt;
  
  
  Second Case: Simple Property Set Asynchronously
&lt;/h4&gt;

&lt;p&gt;Here’s the example:&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-qpmk1zbe?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
Without Zone.js, asynchronous changes like setInterval don’t automatically update the UI, we can fix this by calling:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.changeDetectorRef.markForCheck();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s the corrected version:&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-zgsn3pst?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
Alternatively, we can use &lt;em&gt;signals&lt;/em&gt; for a cleaner solution: &lt;/p&gt;

&lt;p&gt;Here’s the updated version:&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-vupgk78e?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;In Summary:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;tick = signal(0);&lt;/code&gt; instead of &lt;code&gt;tick = 0;&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Replace &lt;code&gt;this.tick += 1;&lt;/code&gt; with &lt;code&gt;this.tick.update((value) =&amp;gt; value + 1);&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Call &lt;code&gt;tick()&lt;/code&gt; in the HTML instead of directly using &lt;code&gt;tick&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Third Case: Data Retrieved from HTTP and stored in an Array
&lt;/h4&gt;

&lt;p&gt;In this example, you’ll notice that the view is not updated:&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-chcktavd?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
To fix this, we can again use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.changeDetectorRef.markForCheck();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s the corrected version:&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-q2e2dk1y?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;But rather than relying on ChangeDetectorRef, I prefer using async, which automatically updates the view. This leads us to the fourth use case.&lt;/p&gt;

&lt;h4&gt;
  
  
  Fourth Case: Data Retrieved from HTTP with Async Pipe
&lt;/h4&gt;

&lt;p&gt;This is straightforward, just apply the &lt;code&gt;async&lt;/code&gt; pipe in the HTML as shown in the following example:&lt;br&gt;&lt;br&gt;
&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-nztsz6ug?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
There’s also a third approach: using &lt;strong&gt;signals&lt;/strong&gt;, similar to what we did in the second case for handling asynchronous scenarios. Here’s how in the following section ...&lt;/p&gt;
&lt;h4&gt;
  
  
  Fifth Case: Data Retrieved from HTTP and Stored in a Signal
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Instead of: &lt;code&gt;users$ = this.getData();&lt;/code&gt; use: &lt;code&gt;usersSignal = toSignal(this.getData(), { initialValue: [] });&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;And in the template, replace: &lt;code&gt;@for(user of users$ | async; track user.id)&lt;/code&gt; with: &lt;code&gt;@for(user of usersSignal(); track user.id)&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/zoneless-angular-xzd3d761?embed=1&amp;amp;file=src%2Fmain.ts&amp;amp;hideExplorer=1" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;br&gt;
In conclusion:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Property Updates in Events&lt;br&gt;
When a property is updated within an event handler (e.g., button click), the UI updates seamlessly, just as before.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Asynchronous Operations&lt;br&gt;
Updating properties asynchronously (e.g., setInterval) requires manual intervention. Without zone.js, Angular is unaware of state changes. You can address this by explicitly calling:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.changeDetectorRef.markForCheck();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This schedules a manual change detection cycle, ensuring the UI updates.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP Requests with Observables
When retrieving data via HTTP and storing it in an array, the UI doesn't update automatically. Use the async pipe in your templates to handle this gracefully:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div *ngFor="let user of users$ | async"&amp;gt;
  {{ user.name }}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The async pipe subscribes to the observable, triggering change detection whenever new data is emitted.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Signals for Change Detection&lt;br&gt;
Angular’s experimental signals offer a powerful alternative. By converting state to signals, Angular registers them as view dependencies. When the signal updates, the UI automatically reflects the changes without manual triggers:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;HTTP Requests with Signals&lt;br&gt;
Convert observables to signals using toSignal():&lt;br&gt;
Angular manages subscriptions automatically, and the UI updates whenever the signal changes.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;On November 19, 2025, with the release of Angular 19, the framework advanced its efforts to enhance and refine zoneless application support. Six months after the initial experimental release, the Angular team has enhanced APIs, introduced support for server-side rendering, and improved the testing experience. While there are still some refinements before the API reaches developer preview, Angular remains committed to iterating on this feature in 2025. Developers are encouraged to explore zoneless in their projects using the Angular CLI:&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng new [project-name] --experimental-zoneless  

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

&lt;/div&gt;



</description>
      <category>angular</category>
      <category>zonejs</category>
      <category>javascript</category>
    </item>
    <item>
      <title>ChangeDetectionStrategy dans Angular (de zéro à héros) - Partie 1/2</title>
      <dc:creator>Houdass Youness</dc:creator>
      <pubDate>Mon, 06 Mar 2023 06:20:04 +0000</pubDate>
      <link>https://dev.to/houdass/changedetectionstrategy-dans-angular-de-zero-a-heros-partie-12-2eij</link>
      <guid>https://dev.to/houdass/changedetectionstrategy-dans-angular-de-zero-a-heros-partie-12-2eij</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.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%2F9cb0pxm0xwstz0actkio.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F9cb0pxm0xwstz0actkio.png" alt="Détection de changement dans Angular" width="800" height="340"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  1- Change Detection Strategy
&lt;/h1&gt;

&lt;p&gt;La stratégie de détection de changement dans Angular régit la manière dont Angular décide s'il faut ou non mettre à jour l'interface utilisateur lorsque le modèle de données change (via l'annotation @Input()). &lt;/p&gt;

&lt;p&gt;En Angular, il existe deux stratégies de détection de changement disponibles.&lt;/p&gt;

&lt;h2&gt;
  
  
  1.1- Default Change Detection Strategy
&lt;/h2&gt;

&lt;p&gt;Cette stratégie de détection des changements est par défaut dans Angular. elle vérifie toutes les propriétés du modèle de données à chaque cycle de rendu pour déterminer si des modifications ont été effectuées. Si des modifications sont détectées, Angular met à jour l'interface utilisateur en conséquence. Cette méthode assure une grande précision, mais peut ralentir les performances des applications complexes qui ont de nombreuses données en constante évolution. Dans ces cas-là, il est recommandé de passer à une stratégie de détection de changements personnalisée pour améliorer les performances.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;NB: Quand il y a un changement, la carte devient jaune.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1.2- OnPush Change Detection Strategy
&lt;/h2&gt;

&lt;p&gt;La stratégie de détection de changements OnPush est une stratégie de performance optimisée. Elle vérifie les modifications uniquement lorsque les données sont explicitement modifiées via des actions telles que des clics de bouton ou des entrées utilisateur, ou lorsque de nouvelles références d'objets ou de tableaux sont fournies. Si aucun changement n'est détecté, Angular ne met pas à jour l'interface utilisateur. Cette stratégie est particulièrement utile pour les applications complexes avec des données statiques. Toutefois, vous devez être prudent lorsque vous utilisez cette stratégie, car si des modifications sont apportées aux données sans en informer Angular, l'interface utilisateur ne sera pas mise à jour.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-sj9rgq?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h1&gt;
  
  
  2- Passage par valeur &amp;amp; par référence
&lt;/h1&gt;

&lt;p&gt;Lorsque nous utilisons la stratégie de détection de changement OnPush, nous devons travailler avec des objets immuables, ce qui représente un contrat que nous signons avec Angular. L'avantage d'utiliser l'immuabilité dans le contexte de la détection de changement est que Angular peut effectuer une vérification simple des références pour déterminer si la vue doit être mise à jour. Ces vérifications sont moins coûteuses qu'une comparaison approfondie. Il est important de noter que les variables sont transmises par valeur, tandis que les objets (y compris les tableaux en JavaScript) sont transmis par référence.&lt;/p&gt;

&lt;h2&gt;
  
  
  2.1- Cas d'une variable primitive
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sayHello(name) {
   name = "Hello " + name;
}

let user = "Angular";
sayHello(user);
console.log(user); // "Angular"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dans cet exemple, la fonction sayHello reçoit une variable primitive name en argument. Lorsque nous appelons cette fonction avec la variable user, qui contient la chaîne de caractères "Angular", la valeur de user ne change pas. Par conséquent, la variable user n'est pas modifiée en dehors du contexte de la fonction. Il est important de comprendre que les chaînes de caractères, les booléens et les nombres sont transmis par valeur.&lt;/p&gt;

&lt;h2&gt;
  
  
  2.2- Cas d'un object / array
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Object
const user = { id: 1, name: 'User1' };
const anotherUser = user;

user.hobby = 'Programming';

console.log(user); // { id: 1, name: 'User1', hobby: 'Programming' }
console.log(anotherUser); // { id: 1, name: 'User1', hobby: 'Programming' }

// Array
const users = ['A', 'B'];
const friends = users;

users.push('C');

console.log(users); // ['A', 'B', 'C']
console.log(friends); // ['A', 'B', 'C']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dans cet exemple, nous créons un objet user avec deux propriétés, id et name, ainsi qu'un tableau users contenant deux éléments. Nous assignons ensuite user à la variable anotherUser, et users à la variable friends. Nous ajoutons ensuite une propriété hobby à l'objet user et un élément C au tableau users. Lorsque nous imprimons user, anotherUser, users et friends, nous pouvons constater que les modifications apportées à user et users ont également été appliquées à anotherUser et friends, respectivement. Cela s'explique par le fait que les objets et les tableaux sont transmis par référence, et non par valeur.&lt;/p&gt;

&lt;p&gt;Il est essentiel de comprendre la différence entre les passages par référence et par valeur, car cela nous permettra de mieux comprendre la manière dont nous passons les données à nos composants Angular via le décorateur @Input(), ainsi que la stratégie OnPush.&lt;/p&gt;

&lt;h1&gt;
  
  
  3- Exemples concrets d'utilisation de la stratégie OnPush avec le passage par valeur/référence
&lt;/h1&gt;

&lt;p&gt;Dans l'exemple ci-dessous, il est possible de constater que le clic sur le bouton ne fonctionne pas comme prévu. En effet, cela est dû à la modification directe de la référence de l'objet via la ligne de code suivante :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.card.title = 'Card 1 title changed !!';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-fnzbhz?embed=1&amp;amp;file=src/app/app.component.html" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Afin d'obtenir le comportement souhaité dans l'exemple précédent, il est nécessaire de changer la référence de l'objet. Cela peut être réalisé en affectant un nouvel objet à la variable, comme suit :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.card = { title: 'Card 1 title changed !!', description: 'Lorem ipsum 1' };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Une autre méthode consiste à utiliser l'opérateur de propagation ("spread operator") pour créer une copie de l'objet existant, puis à remplacer la propriété désirée, comme suit :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.card = { ...this.card, title: 'Card 1 title changed !!' };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Il est par ailleurs possible d'utiliser des méthodes helpers telles que &lt;strong&gt;cloneDeep&lt;/strong&gt; de la bibliothèque &lt;strong&gt;lodash&lt;/strong&gt; ou la méthode native JavaScript &lt;strong&gt;structuredClone&lt;/strong&gt; pour réaliser une copie profonde de l'objet.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-zgwpsx?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  OnPush &amp;amp; l'asynchronisme
&lt;/h3&gt;

&lt;p&gt;Dans l'exemple suivant, lorsqu'on clique sur le bouton "Add synchronically", Angular effectue une détection de changement et met à jour la vue conformément aux modifications apportées.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-1?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Il peut sembler logique que cela fonctionne avec toutes les API asynchrones qui déclenchent la détection de changement, mais ce n'est malheureusement pas le cas. En effet, un clic sur le bouton "Add Asynchronically" ne fonctionnera pas.&lt;/p&gt;

&lt;p&gt;Notez que l'asynchronisme peut être déclenché par l'utilisation de certaines fonctions telles que setTimeout, setInterval, des Promises et Http, entre autres.&lt;/p&gt;

&lt;h1&gt;
  
  
  4- Lancer la "Change Detection" explicitement.
&lt;/h1&gt;

&lt;p&gt;Angular nous fournit un moyen pour déclencher nous-mêmes la détection de changements lorsque cela est nécessaire.&lt;/p&gt;

&lt;p&gt;Une des méthodes pour déclencher manuellement la détection des changements dans Angular est d'utiliser la fonction detectChanges(). Cela permet d'indiquer à Angular d'exécuter la détection de changements sur le composant et ses enfants.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-1-ntyrcb?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h1&gt;
  
  
  5- Async Pipe
&lt;/h1&gt;

&lt;p&gt;Le pipe async souscrit à un observable ou une promesse et renvoie la dernière valeur qu'il a émise.&lt;/p&gt;

&lt;p&gt;Voyons un exemple simple d'un composant qui utilise la stratégie OnPush et qui reçoit un observable en entrée (@input()).&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-2-s2u9fc?embed=1&amp;amp;file=src/app/card/card.component.html" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Lorsque nous cliquons sur le bouton, nous ne verrons pas la vue mise à jour. Cela est dû au fait qu'aucune des conditions mentionnées ci-dessus ne s'est produite, Angular ne vérifiera donc pas le composant lors du cycle de détection de changement actuel.&lt;/p&gt;

&lt;p&gt;Une solution possible consiste, comme expliqué précédemment, à utiliser la méthode detectChanges() pour déclencher explicitement la détection de changements.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-2-deqthy?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Très bien ! Utilisons maintenant le pipe async.&lt;/p&gt;

&lt;p&gt;Le pipe async est un moyen pratique de gérer des valeurs asynchrones dans un template Angular. Il souscrit automatiquement à un observable ou à une promesse et retourne la dernière valeur émise.&lt;/p&gt;

&lt;p&gt;Dans notre cas, nous pouvons utiliser le pipe async pour notre observable cards$ et Angular se chargera automatiquement de détecter les changements et de mettre à jour la vue lorsque la valeur de l'observable change.&lt;/p&gt;

&lt;p&gt;Voici comment nous pouvons utiliser le pipe async dans notre example:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://stackblitz.com/edit/angular-performances-onpush-2?embed=1&amp;amp;file=src/app/app.component.ts" width="100%" height="500"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h1&gt;
  
  
  6- Conclusion
&lt;/h1&gt;

&lt;p&gt;Dans cet article, nous avons examiné les deux stratégies de détection de changement disponibles dans Angular, à savoir la stratégie &lt;strong&gt;par défaut&lt;/strong&gt; et la stratégie &lt;strong&gt;OnPush&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Nous avons souligné l'importance de travailler avec des objets immuables lors de l'utilisation de la stratégie OnPush et expliqué les différences entre les passages par référence et par valeur. &lt;/p&gt;

&lt;p&gt;En outre, nous avons fourni des exemples pratiques d'utilisation de la stratégie OnPush avec le passage par valeur/référence et nous avons également illustré l'utilisation concrète le pipe async.&lt;/p&gt;

&lt;p&gt;J'espère que cet article vous a été bénéfique, une deuxième partie de cet article sera bientôt disponible, nous aurons l'occasion de nous retrouver pour approfondir davantage le sujet.&lt;/p&gt;

</description>
      <category>blockchain</category>
      <category>web3</category>
      <category>announcement</category>
      <category>devto</category>
    </item>
  </channel>
</rss>
