The @Input directive is not compatible with the OnPush change detection strategy

page.html

<app-parcel-delivery-cost-promo [parcelDeliveryCost]="parcelDeliveryCost">
  </app-parcel-delivery-cost-promo>

page.ts

changeDetection: ChangeDetectionStrategy.OnPush,

parcelDeliveryCost: Partial<ParcelDeliveryCostModel>;

  ngOnInit(): void {
     this.translateService.get(['Client.Parcel-Delivery-Cost']).subscribe(res => {

      this.parcelDeliveryCost = {
        title: res['Client.Parcel-Delivery-Cost'],
        description: res['Client.Parcel-Picked-Up-From-The-Location-And-Delivered-To-You'],
        cost: environment.parcelDeliveryCost
      };
    });
  }

component.ts

 changeDetection: ChangeDetectionStrategy.OnPush,

export class ParcelDeliveryCostPromoComponent implements OnInit {

  @Input() parcelDeliveryCost: ParcelDeliveryCostModel;

  constructor() { }

  ngOnInit(): void { }

}

componet.html

<ion-grid>
  <ion-row>
    <ion-col size="12" >
      <h5 class="font-bold margin-top-bottom-5">{{parcelDeliveryCost?.title}}</h5>
    </ion-col>
    <ion-col size="12">
      <div class="color-medium">{{parcelDeliveryCost?.description}}</div>
    </ion-col>
    <ion-col size="12">
      <h4 class="margin-top-bottom-5 text-line-through">{{parcelDeliveryCost?.cost}}</h4>
    </ion-col>

  </ion-row>
</ion-grid>

Q: Can you explain the behavior of @Input not working with OnPush change detection in this code? What could be causing the issue, such as the app-parcel-delivery-cost-promo component not displaying until a page modification is made?

Answer №1

When using input, everything seems to work smoothly. However, when implementing Subscription in ngOnInit with the OnPush strategy, the change detection does not get triggered as expected. To resolve this issue, consider one of the following options:

  • Manually run the change detector within the subscription.
  • Replace .subscribe() with the async pipe (which automatically runs markForCheck).
  • Disable the OnPush strategy altogether.

Answer №2

Give this a shot

 let updatedParcelDeliveryCost = Object.assign({},{
        title: res['Client.Parcel-Delivery-Cost'],
        description: res['Client.Parcel-Picked-Up-From-The-Location-And-Delivered-To-You'],
        cost: environment.parcelDeliveryCost
      });

Angular triggers change detection when the reference of an object is modified.

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

Encountering an issue with TypeScript error code TS2322 when trying to assign a className to the @

Encountering a typescript error when trying to apply a className to a Box element. Interestingly, the same code works on other developers' machines with almost identical configurations. Current dependencies: "@material-ui/core": "4.11. ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...

Unable to locate module: The system was unable to find the specified module '@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js'

After encountering an error with Mat Dialog boxes close button not working on IOS devices (refer to Stack Overflow), I decided to downgrade my Angular project from version 14.0.0 to 13.0.0. I followed a solution provided in another Stack Overflow thread. H ...

Exploring the Potential of Jest in Combination with Angular 13 and Clarity Framework

I am in the process of upgrading an existing Angular application that utilizes VMware Clarity. After successfully updating from version 8.x to 10.x by following the Angular update guidelines, I encountered an issue with the jest configuration when attempti ...

Creating Excel documents using Angular and XLSX template generator

In my Angular application, I am utilizing the XLSX library to manipulate an Excel file. The file I start with is encoded in base64 format, so my first task is to decode it, make some changes to specific cells, and then save the modified file back in base64 ...

Warning: The attribute 'EyeDropper' is not recognized within the context of 'Window & typeof globalThis'

Attempting to utilize "window.EyeDropper" in a project that combines vue2 and TypeScript. When writing the following code: console.log(window.EyeDropper); An error message is generated by my Vetur plugin: Property 'EyeDropper' does not exist on ...

Tips for passing a query parameter in a POST request using React.js

I am new to working with ReactJS and I have a question about passing boolean values in the URL as query parameters. Specifically, how can I include a boolean value like in a POST API call? The endpoint for the post call is API_SAMPLE: "/sample", Here is ...

Exploring the implementation of initiating paypal in NestJs using Jest testing framework

Currently, I am creating a test for a method within NestJs that is responsible for initiating a Paypal Payment intent. When I execute either the yarn test:watch or simply yarn test command, the test described below runs successfully and passes. However, up ...

Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

What could be causing my website to lose its responsiveness after linking a domain?

Recently, I created a basic website for an event in my town using AWS Amplify from Amazon. Initially, the website was hosted without a custom domain and had a random URL. It worked well on both web and mobile platforms. However, after connecting a custom d ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively. When using expect(x).toHaveBeenCalledWith(someParams);, it requires a spy to be used. However, I am unsure of how to spy ...

Angular encountered an error: spawn UNKNOWN was not handled

Within my Angular-13 project, everything had been running smoothly. However, out of nowhere, I encountered an error when trying to run ng serve: An unhandled exception occurred: spawn UNKNOWN See "C:\Users\JOSHU~1.IBE\AppData\Local ...

unable to retrieve JSON sub-elements

I encountered an issue while attempting to iterate through the JSON object provided. When trying to access the content-items using page.content-items, I received an error message. Is it possible to access an object that has a key with "-" in its name? Co ...

When sending a POST request in Angular and Node.js, the req.body object is found to be empty {}

Presenting My Service Module import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Items } from "./inventory.model"; import { Router } from "@angular/router"; impor ...

Display the data in ngx-charts heat map

I have been utilizing ngx charts to display data in a Heat Map. The implementation is smooth without encountering any issues. View Working Example | Heat Map However, I am interested in displaying the values of each grid rather than just on mouse hover. ...

How to invoke a method in a nested Angular 2 component

Previous solutions to my issue are outdated. I have a header component import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Observable } from 'rxjs/Observable'; ...

Determine in JavaScript if one date occurs exactly one week after another date

Currently, I am tackling a date comparison task for our application. The main objective is to compare the Start Date inputted by the user with the Operator/Region Effective Date, which signifies when a new list of product prices becomes valid. Our aim is t ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...