<?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: BhanuprakashReddy</title>
    <description>The latest articles on DEV Community by BhanuprakashReddy (@imbhanu47).</description>
    <link>https://dev.to/imbhanu47</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%2F1074735%2F2c39fffe-41c0-43fb-b918-e4e4274a97f6.jpeg</url>
      <title>DEV Community: BhanuprakashReddy</title>
      <link>https://dev.to/imbhanu47</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/imbhanu47"/>
    <language>en</language>
    <item>
      <title>Angular 16 Signals a new way of managing application state.</title>
      <dc:creator>BhanuprakashReddy</dc:creator>
      <pubDate>Mon, 15 May 2023 13:31:06 +0000</pubDate>
      <link>https://dev.to/imbhanu47/angular-16-signals-a-new-way-of-managing-application-state-2aim</link>
      <guid>https://dev.to/imbhanu47/angular-16-signals-a-new-way-of-managing-application-state-2aim</guid>
      <description>&lt;p&gt;&lt;strong&gt;Before going into the topic let's brief …How Angular currently deals with reactive state management.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;we all know that In Angular, the primary way to manage state changes is through services, components, and data binding using properties and events or RxJs. Angular provides features like two-way data binding, event binding, and property binding to facilitate the flow of data between components and their templates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On the other hand, &lt;a href="https://www.solidjs.com/"&gt;Solid.js&lt;/a&gt; is a separate JavaScript library that introduces the concept of "Signals" for managing reactive state in web applications. It is not directly related to Angular. But now in Angular 16 they introduced the concept of signal (Still under developer preview) included in @angular/core.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;What is this Signal actually… ?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Signals are a new way of managing state changes in Angular applications, inspired by Solid.js. Signals are functions that return a value (get())and can be updated by calling them with a new value (set()). Signals can also depend on other signals, creating a reactive value graph that automatically updates when any dependencies change. Signals can be used with RxJS observables, which are still supported in Angular v16, to create powerful and declarative data flows.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Signals offer several advantages over the traditional change detection mechanism in Angular, which relies on Zone.js to monkey-patch browser APIs and trigger change detection globally. Signals allow you to run change detection only in affected components, without traversing the entire component tree or using Zone.js. This improves runtime performance and reduces complexity.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I know this theory is boring.  Let's dive into the action.&lt;/p&gt;

&lt;p&gt;Let's say you have an e-commerce application where users can add items to their shopping cart. You want to display the total price of the items and update it every time a new item is added or removed. Here's how you can use Signals to achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component({
  selector: 'my-cart',
  template: `
    &amp;lt;ul&amp;gt;
      &amp;lt;li *ngFor="let item of items"&amp;gt;
        {{item.name}} - ${{item.price}}
        &amp;lt;button (click)="removeItem(item)"&amp;gt;Remove&amp;lt;/button&amp;gt;
      &amp;lt;/li&amp;gt;
    &amp;lt;/ul&amp;gt;
    Total Price: ${{totalPrice()}}
  `,
})
export class CartComponent {
  items = [    { name: 'Product A', price: 10 },    { name: 'Product B', price: 15 },    { name: 'Product C', price: 20 },  ];

  // Define a signal for the list of items
  itemList = signal(this.items);

  // Define a computed value for the total price
  totalPrice = computed(() =&amp;gt; {
    return this.itemList().reduce((acc, curr) =&amp;gt; acc + curr.price, 0);
  });

  removeItem(item) {
    // Update the itemList signal by removing the selected item
    this.itemList.set(this.itemList().filter((i) =&amp;gt; i !== item));
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we define a signal itemList for the list of items in the cart and a computed value totalPrice that depends on itemList. Whenever an item is removed from the cart, we update the itemList signal which triggers the re-calculation of totalPrice.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;using &lt;strong&gt;Computed&lt;/strong&gt;() we can recalculate several other signal values if some signal changes.&lt;br&gt;
If there is any change in signal that notifies all the dependant who listens to it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;`// To set a value of a signal you call the function signal like&lt;br&gt;
variableName = signal(value);&lt;/p&gt;

&lt;p&gt;//And to get the value out of the signal you call the variableName as a function like&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;{{ variableName() }}&lt;/p&gt;`

&lt;p&gt;To change the value of a signal there are 2 methods available. Update and mutate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;variableName = signal&amp;lt;any&amp;gt;({
 a: 'Test'
});

variableName.mutate(
 currentValue =&amp;gt; currentValue.b = 'Another Test';
);

//or

variableName = signal&amp;lt;CustomerItem[]&amp;gt;([
  {
    customer: 'Bhanu'
  }
]);

variableName.mutate(
  customerArray =&amp;gt; customerArray.push = {
    customer: 'Prakash'
  };
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Effect&lt;/strong&gt;&lt;br&gt;
Effects are a concept that developers might already know from NGRX. Besides just getting the value by calling the signal by name like variableName(), they trigger an action that has no impact on the signals value but is executed when the value of the signal changes. The effect is also triggered when the function is executed for the first time. This means you can not only define it and it will be triggered once the signals value changes. Its executed the first time the code runs over the effect.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public weatherData$: Observable&amp;lt;WeatherData&amp;gt;;
public dateSignal = signal&amp;lt;Date&amp;gt;(Date.now());

public effectRef = effect(
 () =&amp;gt; {
  this.weatherData$ = this.httpClient.get&amp;lt;WeatherData&amp;gt;('/weatherData?date=' + dateSignal());
 }
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the effect had an if else statement in it where one signal was in the if and another signal was in the else statement. It will register to both signals. But it is only executed when one of those 2 signals change. It's not executed when a third signal changes that is not mentioned in the effect.&lt;br&gt;
The effect() function returns an Effect. It can be manually scheduled or destroyed. There are 3 methods on the Effect.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;schedule(): Schedule the effect for manual execution.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;destroy(): Shut down the effect, removing it from any upcoming scheduled executions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;consumer: Direct access to the effect's Consumer for advanced use cases.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;computed&lt;/strong&gt;&lt;br&gt;
The computed function is like an effect. The difference is that it returns a new (and immutable) signal of type Signal instead of an Effect. This means that we can recalculate several other signal values if some signal changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {  Component, computed, SettableSignal, signal, Signal } from '@angular/core';

@Component({
 selector: 'signal-test-component',
 template: '{{valueX()}}'
})
export class SignalTestComponent {
 public valueX: SettableSignal&amp;lt;number&amp;gt; = signal&amp;lt;number&amp;gt;(5);
 public valueY: SettableSignal&amp;lt;number&amp;gt; = signal&amp;lt;number&amp;gt;(5); 
 public valueZ: Signal&amp;lt;number&amp;gt;;

 constructor() {
  console.log('The number is: ' + valueX());
  this.valueZ = computed(
   () =&amp;gt; this.valueX() + this.valueY()
  );
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;valueZ will always depend on valueX and valueY and therefore has no methods to update or mutate. It does not need them. That's the difference between a SettableSignal and a Signal.&lt;/p&gt;

&lt;p&gt;Nice visual explained by &lt;a href="https://medium.com/r/?url=https%3A%2F%2Fyoutu.be%2Fn5023Q7vGr0"&gt;TeckShareSkk&lt;/a&gt;&lt;br&gt;
Sample E-Comm App using &lt;a href="https://medium.com/r/?url=https%3A%2F%2Fgithub.com%2Fuibhanu5%2FAngular-16-Signals%2Ftree%2Fmaster"&gt;Angular 16 Signals&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I hope you find this post helpful. Thanks for reading.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>angular16</category>
      <category>angular</category>
      <category>solidjs</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Improving Angular Rendering Performance with TrackBy and Change Detection Strategy</title>
      <dc:creator>BhanuprakashReddy</dc:creator>
      <pubDate>Mon, 08 May 2023 17:39:31 +0000</pubDate>
      <link>https://dev.to/imbhanu47/improving-angular-rendering-performance-with-trackby-function-and-change-detection-strategy-1llj</link>
      <guid>https://dev.to/imbhanu47/improving-angular-rendering-performance-with-trackby-function-and-change-detection-strategy-1llj</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Flickering in Angular applications can be caused by inefficient rendering, which can happen when the browser has to re-render the entire DOM for a component or list every time a change occurs. This can be especially problematic for large or complex applications.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To prevent flickering, developers can use the TrackBy function and OnPush change detection strategy to improve performance and reduce unnecessary rendering. These techniques can help provide a better user experience in Angular apps. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Lets dive into the Action&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Let's say you have a component that displays a list of ITEMS, and each item has an ID, a name, and a description. The list is updated frequently, either by adding new items or by changing the properties of existing items. You want to make sure that when the list is updated, only the items that have changed are re-rendered, and not the entire list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This is where the TrackBy function comes in. The TrackBy function is used to tell Angular how to track changes in the list items, so that it can identify which items have changed and only update those.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// item.component.ts
@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
})
export class ItemComponent {
  @Input() item: Item;
}

// item.component.html
&amp;lt;div&amp;gt;
  &amp;lt;h2&amp;gt;{{ item.name }}&amp;lt;/h2&amp;gt;
  &amp;lt;p&amp;gt;{{ item.description }}&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;

// list.component.ts
@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent {
  items: Item[];

  constructor(private service: ItemService) {
    this.items = this.service.getItems();
  }

  trackByFn(index: number, item: Item) {
    return item.id;
  }
}

// list.component.html
&amp;lt;ul&amp;gt;
  &amp;lt;li *ngFor="let item of items; trackBy: trackByFn"&amp;gt;
    &amp;lt;app-item [item]="item"&amp;gt;&amp;lt;/app-item&amp;gt;
  &amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;

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

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In above example, we have an Item component that displays the details of a single item, and a List component that displays a list of items using the *ngFor directive. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The trackByFn function is used to tell Angular how to track changes in the list items. In this case, we're using the item's ID as the key to track changes. This means that when a new item is added to the list or an existing item's properties are changed, Angular will only re-render the specific item, instead of re-rendering the entire list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;By using the TrackBy function in this way, we can significantly improve the rendering performance of our Angular application, especially for large or complex lists.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Change Detection Strategy
&lt;/h2&gt;

&lt;p&gt;In this section, we'll explain how the change detection strategy can help improve application performance.&lt;/p&gt;

&lt;p&gt;before getting into the point let's discuss what is this changeDetectionStrategy in Angular.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; Change Detection is the process by which Angular keeps track of changes in a component's state and updates the view accordingly. By default, Angular uses the "Default".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Change Detection Strategies in Angular:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Default&lt;/strong&gt;: This is the default Change Detection Strategy in Angular. It checks every component and its children for changes on each cycle of the event loop.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;OnPush&lt;/strong&gt;: This Change Detection Strategy checks for changes only when the component's @input properties change, or when an event is fired from the component or one of its children. we need to add a &lt;strong&gt;changeDetection&lt;/strong&gt; property in &lt;strong&gt;component decorator&lt;/strong&gt; to use this.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component({
  selector: 'app-example-list',
  templateUrl: './example-list.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleListComponent implements OnInit {
  @Input() items: ExampleItem[];

  trackByFn(index: number, item: ExampleItem): number {
    return item.id;
  }
}


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

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Detached&lt;/strong&gt;: This Change Detection Strategy disables Change Detection for the component and its children. This can be useful when a component is not expected to change, or when we want to manually trigger Change Detection later. With the Detached strategy, Angular will not check for changes in the component or its children until we manually trigger Change Detection using the ChangeDetectorRef.detectChanges() method.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;However, we should be careful and make sure to manually trigger Change Detection when necessary to avoid issues with the view not updating correctly.&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;@Component({
  selector: 'app-large-list',
  templateUrl: './large-list.component.html',
  changeDetection: ChangeDetectionStrategy.Detached
})
export class LargeListComponent {
  @Input() items: LargeListItem[];
  private isListVisible = false;

  constructor(private cd: ChangeDetectorRef) {}

  showList(): void {
    this.isListVisible = true;
    this.cd.detectChanges();
  }
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;I hope you find this post helpful. Thanks for reading.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>typescript</category>
      <category>angularperformanceimprovement</category>
    </item>
    <item>
      <title>Dynamically Load a Component in Angular on Demand basis (Runtime)</title>
      <dc:creator>BhanuprakashReddy</dc:creator>
      <pubDate>Mon, 01 May 2023 11:20:04 +0000</pubDate>
      <link>https://dev.to/imbhanu47/dynamically-load-a-component-in-angular-based-on-event-b9</link>
      <guid>https://dev.to/imbhanu47/dynamically-load-a-component-in-angular-based-on-event-b9</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In Angular, we can load components dynamically on Demand basis or runtime. this will improve application performance. Instead of loading all components upfront, we can load only the required components when needed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;One common way to dynamically load components is by using the ComponentFactoryResolver service. This service allows us to create a factory for a component, which can then be used to instantiate the component dynamically at runtime.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To implement dynamic component loading, we can first create a host element in the template where the component will be rendered. Then, we can use the ComponentFactoryResolver service to create a factory for the desired component. &lt;br&gt;
We can use the factory to create an instance of the component and attach it to the host element.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This approach helps to reduce the initial bundle size by loading only the required components at runtime. It can also improve the user experience by reducing the initial load time of the application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In some cases you may want to create components dynamically at runtime, rather than including them in your template statically. For example, if you're creating a modal dialog that needs to be displayed on demand, you might want to create the dialog component programmatically instead of including it in the template directly.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;let's get into action&lt;/strong&gt;......&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;In Our Home Component first, create the host element in the template.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div #container&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;button (click)="loadComponent()"&amp;gt;Load Component&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Then, in the component class, inject the ComponentFactoryResolver service and create a reference to the host element:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { PopupComponent } from './popup.component';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) { }

  loadComponent() {
    // Create a factory for the PopupComponent
    const factory = this.resolver.resolveComponentFactory(PopupComponent);

    // Create an instance of the PopupComponent
    const componentRef = this.container.createComponent(factory);
  }
}

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

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;then create PopupComponent
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';

@Component({
  selector: 'app-popup',
  template: '&amp;lt;div&amp;gt;Popup Component&amp;lt;/div&amp;gt;',
})
export class PopupComponent {}

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

&lt;/div&gt;



&lt;p&gt;When the "Load Component" button is clicked, the loadComponent() method is called. This method uses the ComponentFactoryResolver service to create a factory for the PopupComponent. It then uses the factory to create an instance of the component and attach it to the host element (container). This will render the PopupComponent in the DOM.&lt;/p&gt;

&lt;p&gt;finally the Popup component is loaded after click event in Home component.&lt;/p&gt;

&lt;p&gt;I hope you find this post helpful. Thanks for reading.&lt;/p&gt;

</description>
      <category>angular</category>
      <category>angulardynamiccomponentloading</category>
      <category>typescript</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
