The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below is an outline of my approach:

myArray=[];
ngOnChanges(changes:SimpleChanges):void{
  console.log(changes);
  if(changes.myInput.currentValue != undefined && changes.myInput.currentValue != changes.myInput.previousValue){
    for(var i=0;i<this.changes.myInput.currentValue.length;i++){
    console.log("length is" , i);
    this.myArray.push(this.changes.myInput.currentValue);
    }
  }
}

The issue here is that console.log(changes) is only executed once. Despite the fact that the content within it updates whenever @Input() changes. The myInput.currentValue variable holds an array, and my intention is to perform a certain action every time a new object is added to the array through @Input() from the parent component. Unfortunately, it never enters the if condition, and the length cannot be determined.

Answer №1

When myInput.currentValue is an array, and I need to take action each time a new object is added to the array through @Input() from its parent.

The issue arises because the input's value (i.e., reference) remains unchanged when the object within it is mutated. This causes the change detection mechanism to overlook the modification. Instead of using:

myArray.push(newValue);

in the parent component, you should use:

myArray = [...myArray, newValue];

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 resolving a local variable during the execution of a test with Protractor

I'm currently learning about async calls in protractor as a newbie to the tool. I am struggling to figure out how to handle a boolean variable that I set to true if any test case fails and the execution goes to the catch block for a promise. Below is ...

Is it possible to monitor the progress of an order placed via my website as a Flipkart affiliate?

As an affiliate for flipkart, I promote their products on my website. I am interested in being able to track the orders and purchases made by users who are redirected to flipkart from my site. Is it possible for us to obtain the order/purchase id for thos ...

Transferring a JavaScript variable to PHP using AJAX does not display any output

My code is not working as expected. I am trying to pass a JavaScript variable with Ajax to PHP when the submit button is clicked, but the result does not display the var_data variable from JavaScript. Can someone help me identify what is wrong with my code ...

What are the best ways to utilize getElementById in React?

As a beginner in React, I am attempting to create an auto text animation for my project. While I have successfully implemented it in VanillaJS, I am facing challenges with doing the same in React. import React, { Component } from 'react' class A ...

A Guide to Iterating Through Arrays of Objects Using TypeScript

Currently, I am engrossed in an Angular project where I am fetching an object containing an array of objects from an API. The object being passed to the API as a parameter through my service is called "reportData". Here is an example of the data retrieve ...

Dealing with Errors in Angular 2/4 using forkJoin for Multiple URLs

I am currently using Angular 2 and implementing forkJoin for a particular scenario where I need to make multiple REST calls in parallel. Below is the function I am using: private getBatchObservableData(data: Array<Widget>): Observable<any> { ...

The callback function in AngularJS' $http is failing to trigger

$scope.submitNewUser = function() { $http({ method: 'POST', url: 'api/user/signup', data: {'user': $scope.user}, headers: {'Content-Type': ...

Having trouble launching my node application on port 80 on Ubuntu 16.04

Trying to run my node app on port 80 in Ubuntu 16.04 is proving to be a challenge. Despite the fact that the port is not in use, when attempting to start my app with npm start, an error message stating "Port already in use" is displayed. According to infor ...

Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

iPad problem resolved: Disable click hover and double-click issue

I'm experiencing a problem with my web application specifically on Safari for iPad. I have to click twice in order to actually perform the click on the <a> tag. The first click triggers a hover effect, similar to when you hover with a mouse on d ...

Is there a way to make an input field mandatory in Gravity Forms by utilizing javascript or jquery?

I am currently in the process of developing a registration form for an upcoming event using gravity forms. The objective is to allow users to register only if the number of participants matches the number of available shirts. In case they do not match, the ...

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...

No response observed upon clicking on the li element within the personalized context menu

I created a custom context menu that pops up when you click on an li element within an unordered list. I'm trying to trigger an alert when clicking on an li item inside the context menu, but it's not working as expected. To handle this dynamic c ...

Is it possible to utilize instanceof to verify whether a certain variable is of a class constructor type in TypeScript?

I am currently facing an issue with a function that takes a constructor as a parameter and creates an instance based on that constructor. When attempting to check the type of the constructor, I encountered an error. Below are some snippets of code that I ...

Guide to saving an Object to a file (JSON) within the project directory using React Native for Debuggingpurposes

Feeling a bit overwhelmed trying to tackle this issue. My goal is to save data to a JSON file in real-time while debugging my application. I have a Redux store state that I want to organize neatly in a file for easier debugging, so exporting/writing the ob ...

Creating a CSS Grid with Scroll Snap functionality to mimic an iPhone screen in HTML

I have created an iPhone simulator using HTML. It's in German, but I can provide a translation if needed: // JavaScript code for various functionalities related to the iPhone interface /* CSS styling for the iPhone interface */ <meta name="v ...

Node.js server allows for accessing AJAX requests seamlessly

I need to send a parsed AST of JavaScript code to a server for processing, and then receive a list of completions back. However, when I log the AST to the client console before sending it, the structure appears like this: [ { "id":0, "type":"Program", "ch ...

Adjust the background color using jQuery to its original hue

While working on a webpage, I am implementing a menu that changes its background color upon being clicked using jQuery. Currently, my focus is on refining the functionality of the menu itself. However, I've encountered an issue - once I click on a men ...

Retrieve the text content and identification value from each list item

I've found myself in a frustrating situation where I have an unordered list structured like this: var liList = $("#first").find("li"); var append = ""; for(var i =0; i< liList.length; i++){ var item = $(liList); append += "<option value ...