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 method can be used to verify if a username exists within Angular data?

We want to display online users on a webpage by checking if they are currently active. The current code logs all online users in the console, but we need to show this visually on the page. public isOnline: boolean = false; ... ... ngOnInit() { ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...

Enhance your images with the Tiptap extension for customizable captions

click here for image description I am looking to include an image along with an editable caption using the tiptap extension Check out this link for more information I found a great example with ProseMirror, but I'm wondering if it's possible ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...

The getAuth() helper found in the api directory's Clerk retrieves the following data: { userId: null }

I'm completely stuck here.. Currently working with the clerk and I am looking to access the userId of the current user using the getAuth() helper. For more information, refer to the docs: pages/api/example.ts import { getAuth } from "@clerk/n ...

Insert a new row into the table with a value that is taken from the input fields on the form

view image details I am working on a form that consists of 4 fields: Name, Last name, email, and role. There is also a button. When the button is clicked, the input from the above form should be added as a new row in a table below. ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

Angular reactive forms with Material date picker enables the setting of date in the format of YYYY-MM-DDT00:00:00

I am trying to use Material DatePicker with Moment for date formatting while using reactive forms. Here is the code where I set the value for NextDeliverDate in the .ts file: loadData() { this.getSubscriptionData().subscribe((x) => { this.sub ...

Unexplained Reference Error in Next.js Typescript: Variable Accessed before Initialization

I am currently working on an admin website and encountered the error Block-scoped variable used before its declaration.. I will provide details using images and code. This is my first time seeking help on StackOverflow. Error Message: Block-scoped variab ...

Creating an object instance in Angular 2 using TypeScript

Looking for guidance on creating a new instance in TypeScript. I seem to have everything set up correctly, but encountering an issue. export class User implements IUser { public id: number; public username: string; public firstname: string; ...

Extracting data from HTML elements using ngModel within Typescript

I have an issue with a possible duplicate question. I currently have an input box where the value is being set using ngModel. Now I need to fetch that value and store it in typescript. Can anyone assist me on how to achieve this? Below is the HTML code: ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Retrieving radio button value in Angular 2

Currently, I am attempting to retrieve the radio button value in an Angular 2 project. The radio buttons are defined in index.html as: <input type="radio" id="options1" name="function" value="create"> <input type="radio" id="options2" name="func ...

Encountering a problem in React.js and Typescript involving the spread operator that is causing an error

Could someone assist me with my current predicament? I attempted to work with TypeScript and utilize the useReducer hook. const initialState = { a: "a" }; const [state, dispatch] = useReducer(reducer, {...initialState}); I keep encountering an error ...

What is the best way to utilize a React type as props for a custom component?

To make my component work properly, I am required to pass the inputmode as props from an external source. The acceptable values for <input inputMode=<valid values>> are outlined in the React types (node_modules@types\react\index.d.ts) ...

Working with undefined covariance in TypeScript

Despite enabling strict, strictNullChecks, and strictFunctionTypes in TypeScript, the following code remains error-free. It seems that TypeScript is not catching the issue, even though it appears to be incorrectly typed. abstract class A { // You can p ...

Hello, I am looking for a way to maintain a user's active session when transitioning between different Angular applications without constantly prompting them to login. Can you help me

After logging in with my credentials, the session starts. However, if the user does not have an administrator role, I need to redirect them to another application. The challenge is maintaining the active session without requiring the user to log in again ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Troubleshooting Problem in Angular 6: Difficulty in presenting data using *ngFor directive (data remains invisible)

I came across a dataset that resembles the following: Within my app.component.html, I have written this code snippet: <ul> <li *ngFor="let data of myData">{{data.id}}</li> </ul> However, when I execute this code, it only displa ...

Issues with Angular unit tests failing due to an unexpected phantomJS error

Executing ng test triggers the execution of my 3 unit tests which have been hardcoded to pass successfully, as shown below: describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ ...