Welcome to Knowledge Base!

KB at your finger tips

Book a Meeting to Avail the Services of Angular overtime

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All

Angular

Angular - Skipping component subtrees

Skipping component subtrees link

JavaScript, by default, uses mutable data structures that you can reference from multiple different components. Angular runs change detection over your entire component tree to make sure that the most up-to-date state of your data structures is reflected in the DOM.

Change detection is sufficiently fast for most applications. However, when an application has an especially large component tree, running change detection across the whole application can cause performance issues. You can address this by configuring change detection to only run on a subset of the component tree.

If you are confident that a part of the application is not affected by a state change, you can use OnPush to skip change detection in an entire component subtree.

Using OnPush link

OnPush change detection instructs Angular to run change detection for a component subtree only when:

  • The root component of the subtree receives new inputs as the result of a template binding. Angular compares the current and past value of the input with ==
  • Angular handles an event (for example using event binding, output binding, or @HostListener ) in the subtree's root component or any of its children whether they are using OnPush change detection or not.

You can set the change detection strategy of a component to OnPush in the @Component decorator:

      
      import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyComponent {}
    

Common change detection scenarios link

This section examines several common change detection scenarios to illustrate Angular's behavior.

An event is handled by a component with default change detection link

If Angular handles an event within a component without OnPush strategy, the framework executes change detection on the entire component tree. Angular will skip descendant component subtrees with roots using OnPush , which have not received new inputs.

As an example, if we set the change detection strategy of MainComponent to OnPush and the user interacts with a component outside the subtree with root MainComponent , Angular will check all the green components from the diagram below ( AppComponent , HeaderComponent , SearchComponent , ButtonComponent ) unless MainComponent receives new inputs:

An event is handled by a component with OnPush link

If Angular handles an event within a component with OnPush strategy, the framework will execute change detection within the entire component tree. Angular will ignore component subtrees with roots using OnPush, which have not received new inputs and are outside the component which handled the event.

As an example, if Angular handles an event within MainComponent , the framework will run change detection in the entire component tree. Angular will ignore the subtree with root LoginComponent because it has OnPush and the event happened outside of its scope.

An event is handled by a descendant of a component with OnPush link

If Angular handles an event in a component with OnPush, the framework will execute change detection in the entire component tree, including the component’s ancestors.

As an example, in the diagram below, Angular handles an event in LoginComponent which uses OnPush. Angular will invoke change detection in the entire component subtree including MainComponent ( LoginComponent ’s parent), even though MainComponent has OnPush as well. Angular checks MainComponent as well because LoginComponent is part of its view.

New inputs to component with OnPush link

Angular will run change detection within a child component with OnPush setting an input property as result of a template binding.

For example, in the diagram below, AppComponent passes a new input to MainComponent , which has OnPush . Angular will run change detection in MainComponent but will not run change detection in LoginComponent , which also has OnPush , unless it receives new inputs as well.

Edge cases link

  • Modifying input properties in TypeScript code . When you use an API like @ViewChild or @ContentChild to get a reference to a component in TypeScript and manually modify an @Input property, Angular will not automatically run change detection for OnPush components. If you need Angular to run change detection, you can inject ChangeDetectorRef in your component and call changeDetectorRef.markForCheck() to tell Angular to schedule a change detection.
  • Modifying object references . In case an input receives a mutable object as value and you modify the object but preserve the reference, Angular will not invoke change detection. That’s the expected behavior because the previous and the current value of the input point to the same reference.
Last reviewed on Wed May 04 2022

Stay Ahead in Today’s Competitive Market!
Unlock your company’s full potential with a Virtual Delivery Center (VDC). Gain specialized expertise, drive seamless operations, and scale effortlessly for long-term success.

Book a Meeting to Avail the Services of Angularovertime

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular - Slow computations

Slow computations link

On every change detection cycle, Angular synchronously:

  • Evaluates all template expressions in all components, unless specified otherwise, based on that each component's detection strategy
  • Executes the ngDoCheck , ngAfterContentChecked , ngAfterViewChecked , and ngOnChanges lifecycle hooks. A single slow computation within a template or a lifecycle hook can slow down the entire change detection process because Angular runs the computations sequentially.

Identifying slow computations link

You can identify heavy computations with Angular DevTools’ profiler. In the performance timeline, click a bar to preview a particular change detection cycle. This displays a bar chart, which shows how long the framework spent in change detection for each component. When you click a component, you can preview how long Angular spent evaluating its template and lifecycle hooks.

For example, in the preceding screenshot, the second recorded change detection cycle is selected. Angular spent over 573 ms on this cycle, with the most time spent in the EmployeeListComponent . In the details panel, you can see that Angular spent over 297 ms evaluating the template of the EmployeeListComponent .

Optimizing slow computations link

Here are several techniques to remove slow computations:

  • Optimizing the underlying algorithm . This is the recommended approach. If you can speed up the algorithm that is causing the problem, you can speed up the entire change detection mechanism.
  • Caching using pure pipes . You can move the heavy computation to a pure pipe. Angular reevaluates a pure pipe only if it detects that its inputs have changed, compared to the previous time Angular called it.
  • Using memoization . Memoization is a similar technique to pure pipes, with the difference that pure pipes preserve only the last result from the computation where memoization could store multiple results.
  • Avoid repaints/reflows in lifecycle hooks . Certain operations cause the browser to either synchronously recalculate the layout of the page or re-render it. Since reflows and repaints are generally slow, you want to avoid performing them in every change detection cycle.

Pure pipes and memoization have different trade-offs. Pure pipes are an Angular built-in concept compared to memoization, which is a general software engineering practice for caching function results. The memory overhead of memoization could be significant if you invoke the heavy computation frequently with different arguments.

Last reviewed on Wed May 04 2022
Read article

Angular - Resolving zone pollution

Resolving zone pollution link

Zone.js is a signaling mechanism that Angular uses to detect when an application state might have changed. It captures asynchronous operations like setTimeout , network requests, and event listeners. Angular schedules change detection based on signals from Zone.js

In some cases scheduled tasks or microtasks don’t make any changes in the data model, which makes running change detection unnecessary. Common examples are:

  • requestAnimationFrame , setTimeout or setInterval
  • Task or microtask scheduling by third-party libraries

This section covers how to identify such conditions, and how to run code outside the Angular zone to avoid unnecessary change detection calls.

Identifying unnecessary change detection calls link

You can detect unnecessary change detection calls using Angular DevTools. Often they appear as consecutive bars in the profiler’s timeline with source setTimeout , setInterval , requestAnimationFrame , or an event handler. When you have limited calls within your application of these APIs, the change detection invocation is usually caused by a third-party library.

In the image above, there is a series of change detection calls triggered by event handlers associated with an element. That’s a common challenge when using third-party, non-native Angular components, which do not alter the default behavior of NgZone .

Run tasks outside NgZone link

In such cases, you can instruct Angular to avoid calling change detection for tasks scheduled by a given piece of code using NgZone.

      
      import { Component, NgZone, OnInit } from '@angular/core';
@Component(...)
class AppComponent implements OnInit {
  constructor(private ngZone: NgZone) {}
  ngOnInit() {
    this.ngZone.runOutsideAngular(() => setInterval(pollForUpdates), 500);
  }
}
    

The preceding snippet instructs Angular to call setInterval outside the Angular Zone and skip running change detection after pollForUpdates runs.

Third-party libraries commonly trigger unnecessary change detection cycles because they weren't authored with Zone.js in mind. Avoid these extra cycles by calling library APIs outside the Angular zone:

      
      import { Component, NgZone, OnInit } from '@angular/core';
import * as Plotly from 'plotly.js-dist-min';

@Component(...)
class AppComponent implements OnInit {
  constructor(private ngZone: NgZone) {}
  ngOnInit() {
    this.ngZone.runOutsideAngular(() => {
      Plotly.newPlot('chart', data);
    });
  }
}
    

Running Plotly.newPlot('chart', data); within runOutsideAngular instructs the framework that it shouldn’t run change detection after the execution of tasks scheduled by the initialization logic.

For example, if Plotly.newPlot('chart', data) adds event listeners to a DOM element, Angular does not run change detection after the execution of their handlers.

Last reviewed on Wed May 04 2022
Read article