The HostBinding() method is not affected by the OnPush change detection strategy

I have been working on optimizing a complex Angular component that frequently updates data. I have implemented the OnPush change detection strategy, which has significantly reduced the number of calls to property getters. However, I have noticed that HostBindings are still being checked the same number of times as they were with the Default strategy.

Is there something I am overlooking or does OnPush have no impact on HostBindings?

For reference, here is a SlackBlitz example where you can view the console logs: https://stackblitz.com/edit/angular-9w6nwd?file=src/main.ts

Below is a snippet from the example:

  @HostBinding('[attr.style]')
  get styles(): string {
    console.log(`cd count: ${++this.cdCount}`);  // continues to be called the same number of times
    return `--dynamic-height: ${this.calculatedHeight}`;
  }

  cdCount = 0;
  showLinkCount = 0;
  calculatedHeight = 0;

  private _showLink = true;
  set showLink(val: boolean) {
    this._showLink = val;
  }
  get showLink(): boolean {
    console.log(`link count: ${++this.showLinkCount}`); // only checked when calling this.cd.detectChanges()
    return this._showLink;
  }

Answer №1

Angular utilizes ZoneJS internally to patch native JavaScript functions like setTimeout, setInterval, requestAnimationFrame, and more.

This means that each time one of these native functions completes, a signal is sent to Angular prompting it to check for any changes.

To bypass this behavior, opt for Observables instead, which can be managed using operators like filter, distinctUntilChanged, and others.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an optimization error during the docker build process with Ng build

Encountering an error while trying to build an Angular app in docker, specifically when running npm run build: #11 1.106 > ng build #11 1.106 #11 4.769 - Generating browser application bundles (phase: setup)... #11 32.23 ✔ Browser application bundle g ...

Unable to exclude folder while creating production build is not functioning as intended

I've got a directory full of simulated data in the "src/api/mock" folder, complete with ts and JSON files. I'm attempting to have Webpack skip over them during the production build process. I attempted to implement the following rule, but unfortu ...

How to style a parent div with a background class in Angular 6

In my Bootstrap 4 project, I am creating an accordion that consists of cards. Each card contains various icons such as edit, view, and details. When any of these icons are clicked, a function in the component is triggered to navigate the user to a child ro ...

Avoid making API calls in every ngOnInit() function

I am currently developing an Angular front-end for a web-based application. One of the challenges I am facing is that all sub-page drill downs, implemented as different Angular components, make identical API calls in the ngOnInit() method. This repetitiv ...

The classification of a dictionary and a list in Typescript

Can you spot the difference between the two codes below for defining a type of props? I realized that the first one didn't throw a type error, but I can't figure out why my initial second code was incorrect. To me, it seems like it should work p ...

Tips for effectively generating a JSON object array in Typescript

Currently, I'm attempting to construct an array of JSON objects using TypeScript. Here is my current method: const queryMutations: any = _.uniq(_.map(mutationData.result, function (mutation: Mutation) { if (mutation && mutation.gene) { co ...

Utilize JavaScript API for generating and retrieving XSD schema and XML documents

Are there any stable JavaScript APIs that can be used to generate and read XSD schemas and XML documents? My specific requirement is: Allow one user to define/generate an XSD schema through a UI. Later, allow another user to provide appropriate data ...

Tips for combining values with Reactive Forms

Is there a way to merge two values into a single label using Reactive Forms without utilizing ngModel binding? <label id="identificationCode" name="identificationCode" formControlName="lb ...

Highly Transferable Angular Modules for 'ng-cli'

I am managing a system with multiple Angular applications built using the ng-cli: FrontendLibs @company/ core/ src/ package.json index.ts main-app/ src/ package.json In this scenario, I have two Angular applications name ...

Guide on conducting unit tests for the provided code in Angular 8

I am currently working on implementing unit testing for this specific code snippet. applyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); this.DMDataSource.filter = filterValue.trim().toLowerCase(); // con ...

Modify the default behavior of the TabView component in NativeScript

I am currently developing an NS angular2 application and I have run into an issue with the default behavior of the TabView component. I do not want it to preload all data upon creation of the component. Instead, I only want the data for a specific tab to l ...

Maximizing the potential of next.js app router with Redux-Persist

After following the official documentation on integrating Redux with Next.js app router, everything seemed to be working smoothly. However, I encountered challenges when attempting to persist the data using redux-persist. The official Redux docs do not pr ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

What is the proper way to reference a different TypeScript type within comments or JSDoc?

While I am well-versed in Javadoc, there is a feature that allows you to create links referring to the documentation of another type, as discussed here: /** * some java thingy. see this other java thingy too {@link OtherThingy} */ public class Thingy { ...

Steps for updating the value of angular inputs within a function

When a card is selected on the page below, the input values should be updated with information from a JSON object. Here is the JSON data: { "status": true, "data": [ { "id": 1, "pessoa_id": 75505 ...

Loop does not run as expected in TypeScript

Just dipping my toes into TypeScript here, so forgive me if I'm making a rookie mistake. Here's the code snippet I've got: const gCharData: any = {}; function buildChar() { const key = "Char1"; let currentChar = gCharData[k ...

Typescript interface design for nested objects in a hierarchical structure

When data is received from the server in JSON format, it typically looks like the example below (details have been modified): { "apple": { "fruitName": "apple", "types": { "greenApple": { ...

Received a JSON value that cannot be converted into a tuple of two numbers in Typescript

I'm a beginner when it comes to TypeScript and I am struggling to find the solution to my question. In my project, there is a config.json file structured like this: { "api": { "baseUrl": "http://localhost:9000/api", "list": { "itemsP ...

Is there a way to apply Validators.required just once for all required form fields in a Reactive Form?

Latest version of Angular is 4.4.3. In Reactive Form, you can use Validators.required for each form field as shown below: this.loginForm = this.fb.group({ firstName: ['', [Validators.required, Validators.maxLength(55)]], ...

Why is Typescript claiming a property doesn't exist when it clearly does?

Below is the code I am working with: import { useQuery } from "@vue/apollo-composable"; const ACCOUNTS_QUERY = gql` { accounts { id name number } } `; interface Accounts { accounts: [ { id: number; ...