Exploring Transformation in Angular

I am looking to enhance my understanding of how ChangeDetection works, and I have a query in this regard.

When using

changeDetection: ChangeDetectionStrategy.OnPush
, do I also need to check if currentValue exists in the ngOnChanges lifecycle hook, or is it sufficient to just verify if the input has changed?

Allow me to provide an example to clarify my question:

As previously mentioned, with

changeDetection: ChangeDetectionStrategy.OnPush
, I have an input like this:
@Input() isInspectionReopened: boolean;
. My ngOnChanges function looks as follows:

ngOnChanges(changes: SimpleChanges) {
  if(changes.isInspectionReopened) {
     // do something
  }
}

Should I only check changes.isInspectionReopened, or do I also need to consider adding

changes.isInspectionReopened.currentValue
?

Answer №1

SimpleChanges only includes values that have been changed, so if the isInspectionReopened prop remains unchanged, it will not appear there.

When utilizing ChangeDetectionStrategy.OnPush, it is generally recommended to avoid using the ngOnChanges callback entirely. The ChangeDetectionStrategy.OnPush solely impacts the logic governing when change detection should be performed. Thus, a modification to the isInspectionReopened prop triggers change detection because it is an '@Input' property, subsequently updating your component's HTML if bound to the property.

However, in cases where isInspectionReopened is not an '@Input' property (for instance, if the component fetches and updates the value from a server), the OnPush detection mechanism may fail to detect such changes compared to standard change detection. To address this with the OnPush strategy, you can utilize RxJs Observables along with the async pipe to enforce change detection – check out an example here.

It's crucial to note that '@Input' properties prompt change detection exclusively when they are modified through data binding from the parent component. If an '@Input' property's value is altered by the component itself, change detection does not get triggered.

Moreover, component DOM events also trigger change detection. For instance, modifying something within a click handler in response to a click event will always result in the triggering of change detection due to the event itself.

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

Find out if all attributes of the object are identical

I am trying to create the boolean variable hasMultipleCoverageLines in order to determine whether there are multiple unique values for coverageLineName within the coverageLines items. Is there a more efficient way to write this logic without explicitly c ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

Running the Express service and Angular 6 app concurrently

Currently, I am in the process of developing a CRUD application using Angular6 with MSSQL. I have managed to retrieve data from my local database and set up the necessary routes, but I am encountering difficulties when it comes to displaying the data on th ...

Issue - firestore has not been defined (Occurs strictly after the use of "then")

Having an issue: I successfully create fake users in my database, but encounter a problem when starting the 'for' loop. The error I'm facing is: Error adding document: TypeError: Cannot read property 'firestore' of undefined I ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

Error: Trying to access a property that does not exist on an undefined object (retrieving 'kind

Currently, I am working on a project using angular-CLI. When I attempted to create a new module yesterday, an error popped up in the terminal saying Cannot read properties of undefined (reading 'kind') (only this error there wasn't an ...

Implementing nested popup windows using Bootstrap

I am facing an issue with my two-page sign-in and sign-up setup in the header of my angular2 project. On the sign-up page, I have a link that should redirect to the sign-in page when clicked, but I am struggling to make it work. Can someone provide guidanc ...

How can we enhance the angular material date picker by inserting a div on either the left or right side to display

I'm looking to customize the style of an angular material datepicker and include a box that displays the selected date, similar to the image shown here: enter image description here Does anyone have suggestions on how to achieve this? Any assistance ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

App routing functions correctly when navigating within the app, but does not work when directly entering a URL into

After creating an angular 11 app with routing modules, I encountered an issue where typing a specific path in the browser address bar did not navigate to the expected destination. The app functioned correctly when started from the domain URL, leading to th ...

Unusual problem with accessing Object values in vscode using typescript

When attempting to write Object.values in TypeScript, I encounter a visual error (although it compiles without issues). https://example.com/image1.png I have tried searching online and restarting vscode, and here is my current tsconfig.json. https://exa ...

Should the User Id be retrieved within the ngOnIt() function?

Is it considered incorrect to access the User Id within the ngOnIt() method using this.afAuth.auth.currentUser.uid;? I am encountering an issue where uid is undefined when I reload the page, although it works correctly after logging in or being redirect ...

Error in Angular ESLint: The key parameter is mandatory

I'm attempting to download a file using the Angular code below, but I consistently receive an error stating Parameter "key" required const headerValues = new HttpHeaders({ 'Content-Type': contentType!, 'Accept': contentTy ...

What is the best way to remove the underline from Angular Material input fields?

I am currently working with an input element in Angular Material: <md-input-container> <input type="text" mdInput placeholder=""> </md-input-container> While the input is focused, it displays an underline. Is there a way to hide or remo ...

The implementation of CommonJS modules allows for efficient modularization

While using Nx for my Angular workspace, I noticed something that sparked a question in my mind. Why is it necessary to use CommonJS modules in all tsconfig.spec.json files for libs? Looking at Nx examples, I observed that not all libs include it, only app ...

What is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => ...

Utilizing the await keyword within a forkJoin operation in TypeScript

I am facing an issue where I need to fetch a new result based on the old result. When a specific parameter in my primary call is X, it should trigger another function. However, the problem I'm encountering is that the scope of the program continues ru ...

Utilizing an object property for @Input binding in Angular: A step-by-step guide

I am currently delving into Angular and Ionic Frameworks, honing my skills through practice. I'm encountering an issue with a basic @Input test, where I am trying to iterate through an array of Tab Pages and then display each tab using <ion-tab> ...

Validation of Forms and Displaying Error Messages in Angular 7

Please take a look at my straightforward form on Stackblitz https://stackblitz.com/edit/angular-et9uww Within my form, there are 2 checkboxes. When one checkbox is selected, it will populate a corresponding textbox. In this particular scenario, there are ...

Position Bootstrap Modal in the center horizontally

I am working on an Angular project and struggling to center my Bootstrap 3 Modal horizontally on the screen. Despite trying various solutions like using text-align: center and align = "center", I have been unsuccessful. Can someone guide me on how to prope ...