The Angular 2 ngOnchange event is being triggered regardless of whether a change has occurred

Hello everyone,

I am currently facing an issue in my Angular application and I believe it might be due to my lack of experience with Angular.

Specifically, I have noticed that in one of the child components, ngOnChanges is being called even when there are no changes. Upon inspecting the changes object, I found that both currentValues and previousValues properties are the same.

If anyone has any insights or suggestions on what I might be missing, please let me know.

Please refer to the code snippet below as well:

Thank you!

import { Component, Input, SimpleChanges, OnInit} from '@angular/core'; import { OnChanges, OnDestroy } from @angular/core/src/metadata/lifecycle_hooks';

@Component({
selector: 'xxxxxx',
templateUrl: './result.component.html',
styleUrls: ['./result.component.css']    

})

export class ResultComponent implements OnInit, OnChanges, OnDestroy {


@Input()
searchResults: SearchResults.SearchResult;

@Input()
searchText: string;

@Input()
loading: boolean = false;

ngOnInit() {
    var logger = "stop me debugger";
}


ngOnChanges(changes: SimpleChanges) {

    if (changes.searchResults && !changes.searchResults.firstChange) {


    }
}


ngOnDestroy(): void {
    var logger = "stop me debugger";
}



constructor() {


}

}

https://i.sstatic.net/oc9dB.png

Answer №1

The Angular lifecycle method ngOnChanges:

Is triggered when data-bound input properties are (re)set in Angular. This method is passed a SimpleChanges object containing the current and previous property values.
It is called before ngOnInit() and whenever there are changes to one or more data-bound input properties.

Learn more about Angular Lifecycle Hooks here

Due to this behavior, especially when your properties are inputs, the ngOnChanges method is invoked. This is why both the previousValue and the currentValue within the SimpleChanges object are set to undefined.

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

Function for setting specific properties in a Typescript interface

I need help with writing types for a function in TypeScript. I have an interface called "Example" with properties 'num' and 'str'. I want to create a function that takes a key (property name from Example) and a new value for that key. H ...

Customizing Ng2-smart-table cell background color based on the content

I've been experimenting with Ng2-smart-table module (link: ). Wondering if it's possible to personalize the background of a cell or entire row based on the content of that cell or another cell in the same row. Any chance you could show me an exa ...

The Angular Interceptor encounters difficulties in accurately determining the timing of API responses when multiple requests are made simultaneously

Steps to replicate the issue: The initial API call responds in 600ms. While the first API call is being processed, another 4 API requests are sent to the interceptor, which adds an additional second to the process. The problem arises when the interceptor ...

angular2 utilize rxjs to search for threads based on user input

Hey there! I'm working on creating a mini forum inspired by stackoverflow and I'm currently in the process of adding a basic text filter for thread titles. I've recently delved into rxjs and pipes, and this is what I've come up with so ...

Please provide me with the steps to relocate the src/pages/api folder to src/ in a Next.js project

When working with Next.js, I am interested in relocating the src/pages/api directory to be located under src/, much like how it is done in blitz.js. In this case, the directory structure would look something like this: src |- pages |- api Unfortunately, I ...

Retrieve the keys of an interface using generic methods

Recently, I encountered a challenge with a function that utilizes generics. The specific generic in question is <T extends anInterfaceName>. Struggling to retrieve the keys of the interface used in T within the function, my quest for a solution led m ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

Conceal the header and the navigation tabs at the bottom while scrolling - Ionic version 3

Is there a way to conceal the header and footer (tabs at the bottom) as the user begins scrolling down vertically and then bring back the tabs and header when scrolling back up? I would appreciate any tutorials or documentation guides. https://i.sstatic ...

A method for transferring information stored in chrome.storage to a variable within an Angular component

How can I effectively assign data fetched from chrome.storage.sync.get to my Angular component's variable? Below is the code snippet of my component: export class KTableComponent implements OnInit { words: string[] = []; constructor() { } ...

What is the best way to obtain the actual name of a component's method?

Just to clarify the next part: payU serves as the Internet payment operator I'm currently facing a significant challenge when it comes to integrating my Angular app with payU payments. Due to security reasons, I have opted not to store or pass credit ...

Disappearing the button on click in TypeScript

Coding Challenge <button mat-icon-button matTooltip="hi" *ngIf="isValid" (click)="hi(x, y)"> Code Solution isValid: boolean = false; hi(x,y){ this.isValid } I'm facing a challenging coding problem. I am trying ...

Angular - Restarting the inactivity redirection feature upon moving to a different page

I've implemented a feature in my Angular app that redirects users to a screensaver page after 30 seconds of inactivity, using code I found here. The functionality works well, but I'm facing an issue where I don't want the redirection to occu ...

The error encountered states: "TypeError: Unable to access the property 'getGlobalEventTarget' because it is null."

I recently updated the angular version of my project from 4.4.7 to the latest one. I made sure to upgrade my node.js to version 8.11.1 and the angular cli to version 1.7.4 as well. However, upon running the code using npm start, I encountered the followi ...

Guide on integrating a bearer token with an odata source in order to utilize it with a Devextreme dxData Grid

I am using Angular and I am attempting to pass a bearer token through an OData source with a DevExtreme DXDataGrid, but I am facing authentication issues. The error message "Current user did not login to the application!" keeps appearing, indicating that i ...

Angular5: The property 'showNavigationArrows' cannot be bound to 'ngb-carousel' because it is not recognized as a valid property

Currently, I am utilizing ng-bootstrap 1.x.x alongside Angular5 and bootstrap4. My goal is to customize the NavigationArrows based on dynamic data, however, I am encountering an issue while trying to access it from HTML. Here is a snippet of my code: imp ...

Issue with Material UI DateTimePicker not submitting default form value

Currently, I am utilizing React for my frontend and Ruby on Rails for my backend. My issue lies in submitting the value from my materialUI DateTimePicker via a form. The problem arises when I attempt to submit the form with the default DateTime value (whic ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

Maximizing Performance: Enhancing Nested For Loops in Angular with Typescript

Is there a way to optimize the iteration and comparisons in my nested loop? I'm looking to improve my logic by utilizing map, reduce, and filter to reduce the number of lines of code and loops. How can I achieve this? fill() { this.rolesPermiAdd = ...

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...