Detecting changes in Angular from the parent to the child component can be accomplished by utilizing a specific approach

The Sample Component contains data in the form of an array of objects with child components within a loop. Sample.component

export class SampleComponent implements OnInit {
  data = [{ value: 3 }, { value: 1 }];
  constructor() {}

  ngOnInit(): void {}
  valueChange() {
    this.data[1].value = 5;
    this.data = [...this.data];
  }
  whenComponentRerendered() {
    console.log('Parent component rerendered');
  }
  consoleOutput() {
    console.log('Console from button click');
  }
}
<button (click)="valueChange()">
  Change input to 5
</button>
<ng-container *ngFor="let item of data">
  <app-samplechild [data]="item"></app-samplechild>
</ng-container>

It is now necessary to detect changes whenever any value in the object is altered in the parent component.

export class SamplechildComponent implements OnInit {
  @Input('data') data!: any;
  constructor() {}

  ngOnInit(): void {}
  whenComponentRerendered() {
    console.log('child component rerendered');
  }
  changeValue() {
    this.data.value = 5;
  }
}
<p>
  The value from parent is
  {{ data | json }}
</p>

I am facing issues in capturing the changes since the data is not set as an Input value. How can I track changes in the child? StackBlitz Note: This code snippet is for demonstration purposes; in real scenarios, the data may consist of numerous arrays of objects with complex hierarchies.

Answer №1

To fix the issue, simply delete the line

changeDetection: ChangeDetectionStrategy.OnPush
from the SamplechildComponent. This will resolve the problem and allow you to utilize the default Angular changeDetection mechanism.

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

How to process response in React using Typescript and Axios?

What is the proper way to set the result of a function in a State variable? const [car, setCars] = useState<ICars[]>([]); useEffect(() =>{ const data = fetchCars(params.cartyp); //The return type of this function is: Promise<AxiosRespo ...

Having difficulty utilizing the square bracket [ in Angular, despite it being a common feature in standard HTML

Yesterday, while working on my Angular code, I encountered an issue using the rbrack and lbrack. It turns out that Angular throws an error when these are used. Snippet of the code: &lt;gen-pack-comp &lbrack;email&rbrack;="email"" ...

Angular directive compatibility with Mozilla Firefox

I've encountered a strange issue with my directive in Firefox. The directive is designed to limit user input, and it functions correctly in Chrome. However, in Firefox, once the user reaches the input limit, they are unable to delete any characters - ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

In what way can a property in JavaScript alter an object?

I am a newcomer to node.js, although I have been writing Javascript for many years. Recently, I encountered an interesting pattern that has left me puzzled: a Flag that is used to set a modifier on the object. For example, in the socket.io documentation: ...

Switch Cursor on Movable Area in Electron

Working on a project in Electron and having some trouble with a frameless window. I have designated certain top areas as draggable using -webkit-app-region: drag, but the cursor will not change as expected. Although this code snippet won't make the e ...

Unit testing in Angular ensures that a property is always defined and never undefined

I'm struggling to understand why this basic test isn't functioning properly. BannerComponent is not supposed to display a welcome message upon construction Expected 'welcome' to be undefined. // Component @Component({ selector: &ap ...

Identify file size upon upload using Javascript event and allow cancellation

Currently, I am utilizing a file uploader functionality. My preference is to refrain from verifying the file size on the server side. Instead, I am in search of a method that involves monitoring the uploaded file's size periodically through a listener ...

Getting the position (x y coordinates) of moving elements in React Beautiful DND: A step-by-step guide

My question is related to React Beautiful DND - Is there a way to obtain the position (X Y) of objects that are being dragged on the screen? Any suggestions or solutions would be greatly appreciated. Thank you! ...

what is the process for incorporating a unique style in npm mydatepicker?

What is the best way to customize the style of npm mydatepicker? Here is the code I have been using: <my-date-picker [options]="myDatePickerOptions" (dateChanged)="onDateChanged($event)"></my-date-picker> Is it possible to modify its backgrou ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

Angular 2 routing malfunctioning

I'm encountering an issue while setting up routing in my application. The error displayed in the console is as follows: angular2-polyfills.js:138 Error: XHR error (404 Not Found) loading http://localhost:9000/angular2/router.js(…) Below is the co ...

Tips for automatically choosing several choices from a multiple-select using Chosen.JS

I am struggling to programmatically select multiple values in a multiple select using chosenJS/chosen.js while still ensuring that the selected values are bound to my ng-model (angularJS). In this scenario, I have a list of users, some of whom are already ...

Guide on retrieving inline style that has been overridden by CSS using JavaScript

<div style="background: url(http://www.example.com/image.jpg) center center/cover;"> This specific background image defined inline is being replaced by a rule in an external stylesheet: div { background-image: none !important; } Here's my q ...

Locate all elements in an array that contain a particular value for a specific key using Javascript

In my JavaScript data, I have two arrays: ARRAY ONE: [ TextRow { v_id: 3000 }, TextRow { v_id: 3001 }, TextRow { v_id: 3002 } ] ARRAY TWO: [ TextRow { s_id: 'S001', v_id: 3000, type: 'control' }, TextRow { ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...

Explore various THREE.JS 3D models through a clickable link

I am struggling to make each object open a new page using a URL when clicked. No matter what I try, it doesn't seem to work properly. Can someone point out what I might be missing or doing wrong? Here is the click event code for the objects. If needed ...

Having performance issues with an HTML5/JavaScript game on Internet Explorer 8

A new game has been developed using html/javascript. Due to confidentiality reasons, the code cannot be fully shared. The game runs smoothly on most browsers except for IE, which poses a challenge. Compatibility with IE8 is essential, despite its limitati ...

Execute an AJAX post request to the identical PHP page (utilizing the Jquery Form Plugin)

I am in the process of developing a new web interface using JavaTMP, an AJAX-based admin template. After spending time understanding its functionality, I have created a page with a form to allow users to create projects within my software. Typically, creat ...