What could be the reason for ngOnChanges lifecycle hook not getting invoked?

I am currently experimenting with Angular 2 in an effort to learn more about it. I noticed that ngOnChanges is not triggering in the code below:

app.component.ts:

import { Component, Input } from "@angular/core"
import { FormsModule } from '@angular/forms';
import { OnChanges, SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
  selector: 'my-app',
  template: `
    Enter text : <input type="text" [(ngModel)]='userText'  />
    <br/>
    Entered text :  {{userText}} 
  `
})

export class AppComponent {
  @Input()  userText: string;
  name: string = "Tom";

  ngOnChanges(changes: SimpleChanges): void {
    for (let propertyName in changes) {
      let change = changes[propertyName];
      let current = JSON.stringify(change.currentValue);
      let previouis = JSON.stringify(change.previousValue);
      console.log(propertyName + ' ' + current + ' ' + previouis);
    }

  }
}

The above code does not trigger ngOnChanges

However, when I create a separate component called "simple" and use it in app.component.ts, the following setup works correctly:

app.component.ts:

import {Component} from "@angular/core"
import {FormsModule} from '@angular/forms'; 
@Component({
  selector: 'my-app',
  template: `
    Enter text : <input type="text" [(ngModel)]='userText' />
    <br/>
    <simple [simpleInput]='userText'></simple>
  `
})

export class AppComponent{
  userText:string;
  name:string ="Tom";


}

simple.component.ts:

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

@Component({
    selector:'simple',
    template: `You entered {{simpleInput}} `
})
export class SimpleComponent implements OnChanges{
    ngOnChanges(changes: SimpleChanges): void {
        for(let propertyName in changes){
            let change=changes[propertyName];
            let current=JSON.stringify(change.currentValue);
            let previouis=JSON.stringify(change.previousValue);
            console.log(propertyName+ ' '+current+ ' ' +previouis);
        }

    }
    @Input() simpleInput: string;

}

Could someone offer an explanation? What mistake am I making here?

Answer №1

It appears there may be some confusion regarding the purpose of @Input fields. These fields are designed to facilitate communication between parent and child components, rather than being necessary for data binding within a single component. Data binding in a component simply requires that the fields be public.

The ngOnChanges Lifecycle Hook is specifically meant to respond to changes in @Input fields, not changes in HTML input elements.

If you require more advanced change handling beyond two-way data binding, you can try using:

<input type="text" [(ngModel)]='userText' (ngModelChange)="onUserTextChange($event)">

(I apologize if the above code does not work immediately; I will test it and refine it once I am back at my developer workstation.)

You can find additional information here.

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

What is the reason behind the Partial input basic type returning itself?

Snippet of code excerpt: type PartialType<T> = { [P in keyof T]?: T[P]; } I am curious about why the PartialType input basic type (such as string returning string) returns itself instead of throwing an error or an object. // undef => undefined t ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

Mastering the proper usage of the import statement - a guide to seamless integration

I'm excited to experiment with the npm package called camera-capture, which allows me to capture videos from my webcam. As someone who is new to both npm and typescript, I'm a bit unsure about how to properly test it. Here's what I've ...

Creating OpenAPI/Swagger documentation from TypeScript code

I am in search of a solution to automatically create OpenAPI/Swagger API definitions based on my Node.JS/Express.JS/Typescript code. It would be perfect if I could simply add annotations to my Express Typescript base controllers and have the OpenAPI/Swagg ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

extracting the HTML content from JavaScript and saving it into a standalone file

update When I click a link, a popup opens and I see all this HTML. The smile method is called when I click the link, and we append HTML in that method so that we can see it when the popup is opened. I moved it to a separate file something.component.html, ...

A common method for incorporating personalized react-scripts into create-react-app

After creating a project using create-react-app in TypeScript, I am looking to integrate custom react-scripts without ejecting. What is the most effective approach to achieve this? ...

Can the WebSocket interface be substituted with WebSocket itself?

I'm currently in the process of setting up a WebSocket.Server using ws, Express 4, NodeJS, and TypeScript by following a guide. However, I've encountered an issue with the provided code not working as expected from the tutorial found at . In ord ...

Angular 10 - Timezone Detection and Interactive Calendar

I am encountering a major issue with the Angular DateTimePicker and TimeZone functionality. I need to dynamically switch the TimeZone at runtime in my component. Every date displayed on the frontend must be converted, while every date sent to the backend n ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

Learning to implement forwardRef in MenuItem from Material-UI

Encountering an error when pressing Select due to returning MenuItem in Array.map. Code const MenuItems: React.FC<{ items: number[] }> = (props) => { const { items } = props; return ( <> {items.map((i) => { return ( ...

What is the best way to sort through data if I enter more than three characters to filter the results?

Hey there, I'm currently in the process of developing a search bar that functions by displaying only filtered last names from a table when more than 3 characters are typed. The condition for filtering is empty. Here is the HTML code: <mat-form-fi ...

Provide the remaining arguments in a specific callback function in TypeScript while abiding by strict mode regulations

In my code, I have a function A that accepts another function as an argument. Within function A, I aim to run the given function with one specific parameter and the remaining parameters from the given function. Here's an example: function t(g: number, ...

Assigning IDs to Values in Angular 2

Here is the code snippet in question: <select [(ngModel)]=""> <option value="1">New York</option> <option value="2"Phoenix</option> <option value="3">Boston</o ...

html The "download" attribute causing a new tab to open rather than initiating a

I have a website built with Angular 4, where users can download images from an Amazon S3 bucket. However, I encountered an issue wherein instead of downloading the image, it opens in a new tab. I've tested this problem on different browsers such as Fi ...

Tips for solving a deliberate circular dependency in an angular provider

If the existing injection token for this provider is available, I want to use it. Otherwise, I will use the specified provider. Below is the code snippet: providers: [ { provide: DesignerRecoveryComponentStore, useFacto ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

What are the steps to resolve TypeScript errors in OpenLayers version 6.6.1?

Since updating to OpenLayers 6.6.1, I have been bombarded with numerous typescript errors related to generics. For example... import olLayerVector from 'ol/layer/Vector'; import olFeature from 'ol/Feature'; public static highlightOver ...