"Troubleshooting: Why Angular2's ngOnChanges is not triggering with array input

I am currently using a ParentComponent to pass inputs to a ChildComponent. When the input is a number, the ngOnChanges hook successfully fires. However, when it's an array, the hook does not trigger.

Could someone help me identify what I might be doing incorrectly, or provide guidance on how to ensure ngOnChanges fires when the array is modified?

Thank you.

child ts:

export class ChildComponent implements OnInit {
  @Input() num = 0;
  @Input() arr: Array<string> = [];
  constructor() { }

  ngOnInit(): void {
  }

  ngOnChanges() {
    console.log('input changed');
  }

}

parent ts:

export class ParentComponent implements OnInit {

  constructor() { }
  num = 0;
  arr : Array<string> =[];

  ngOnInit(): void {
  }

  changeNumber() {
    this.num = this.num + 1;
  }
  changeArray() {
    this.arr.push('some value');
  }

}

parent html:

<button (click)="changeNumber()">change num</button>
<button (click)="changeArray()">change array</button>
<app-child [num]="num" [arr]="arr"></app-child>

Answer №1

The difference lies in the fact that `num` is considered a primitive data type, while an array is treated as an object. An array functions as an object where the variable `arr` stores the reference. When you add a new element to the array using "push," the reference itself remains unchanged.

This is precisely why the function `ngOnChange` does not trigger. To create a new reference for the array and add a value to it, you can utilize the following code:

this.arr = [...this.arr, 'new value'];

Answer №2

When it comes to detecting changes in arrays, ngOnChanges falls short as it only monitors changes in the array reference itself, not its content. To work around this limitation, you can utilize a setter method.

  private _arr: Array<string> = [];
  @Input() set arr(data) {
    this._arr= data;
    console.log(this._arr);
  };

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

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

IONIC 3 [ERROR] There was a problem encountered during the execution of cordova run android, resulting in an exit code of 1

While trying to run the command 'ionic cordova run android' for Ionic 3, I encountered an error that has left me stumped. Here's a snapshot of the error message: This Result Error [13:29:45] preprocess started ... [13:29:45] deeplinks sta ...

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...

Using Angular 12 to seamlessly import JSON files into TypeScript

My project contains a JSON file located at src/assets/version.json with the following content: {"VERSION":"1.0.0"} I have imported this file into a TypeScript file (e.g., *.ts) as shown below: import * as VersionInfo from 'src/ass ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...

Tips for exporting and reusing third-party types in TypeScript

I am facing a challenge with my package, which relies on a 3rd party package API for most of its functions. How can I export the types from the 3rd party package API in my own package? For instance: React uses @types/react to define its types Let's ...

Is there a way to transform a JavaScript array into a 'name' within the name/value pair of a JSON object?

Suppose I have a dynamic array with an unspecified length, but two specific values are given for this array. var arrName = ["firstName","lastName"]; I need to create a JSON variable that includes the exact values provided for this dynamic array. Here are ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

Tips for fixing the issue of 'expect(onClick).toHaveBeenCalled();' error

Having trouble testing the click on 2 subcomponents within my React component. Does anyone have a solution? <Container> <Checkbox data-testid='Checkbox' checked={checked} disabled={disabled} onClick={handl ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Challenges with incorporating asynchronously fetched data in component operations

I have encountered an issue where the data retrieved from a server in a service is available in the component's template but not in the actual code. This seems strange to me. I made the call in the ngOnInit method of my main AppComponent ngOnInit() { ...

Angular: Employing Pipes for Date Formatting

Looking for assistance with my elevator component. I need to store the date in dd/MM/yy format each time the elevator reaches the first floor. if floor === 1 show Date else return(empty) Check out my StackBlitz project ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

Problem with updating Cypress e2e tests following recent package upgrades

My current project involved updating all the packages to their latest versions. Prior to the update, all end-to-end tests were functioning correctly without any issues. After completing the update, the product itself compiles and runs as expected without ...

Setting up default QueryParamsHandling in Angular

I have successfully developed an angular 9 application and implemented localization using @ngx-translate. To ensure that the app changes locale based on the 'lang' query parameter, I configured it accordingly. @Component({ selector: 'app- ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

Node Express and Typescript app are failing to execute new endpoints

Hello, I'm currently diving into Node express and working on a simple CRUD app for pets. So far, I've successfully created 2 endpoints that are functioning properly. However, whenever I try to add a new endpoint, Postman fails to recognize it, g ...

Convert JSON information into an array and map it in Swift

I am currently facing a certain challenge. My approach involves using Alamofire request to retrieve a JSON response. Alamofire.request(url, method: .get).responseJSON { response in if response.result.isSuccess { print ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Find and extract a specific data set that is repeated in the field multiple times

Currently, I am in the process of developing a game server and have a player inventory that is stored as a json field. My goal is to create a query that specifically retrieves two particular data sets within the field, however, these data sets are repetiti ...