Angular2 change detection: ngOnChanges not firing for nested object
Asked Answered
A

19

187

I know I am not the first to ask about this, but I can't find an answer in the previous questions. I have this in one component

<div class="col-sm-5">
    <laps
        [lapsData]="rawLapsData"
        [selectedTps]="selectedTps"
        (lapsHandler)="lapsHandler($event)">
    </laps>
</div>

<map
    [lapsData]="rawLapsData"
    class="col-sm-7">
</map>

In the controller rawLapsdata gets mutated from time to time.

In laps, the data is output as HTML in a tabular format. This changes whenever rawLapsdata changes.

My map component needs to use ngOnChanges as a trigger to redraw markers on a Google Map. The problem is that ngOnChanges does not fire when rawLapsData changes in the parent. What can I do?

import {Component, Input, OnInit, OnChanges, SimpleChange} from 'angular2/core';

@Component({
    selector: 'map',
    templateUrl: './components/edMap/edMap.html',
    styleUrls: ['./components/edMap/edMap.css']
})
export class MapCmp implements OnInit, OnChanges {
    @Input() lapsData: any;
    map: google.maps.Map;

    ngOnInit() {
        ...
    }

    ngOnChanges(changes: { [propName: string]: SimpleChange }) {
        console.log('ngOnChanges = ', changes['lapsData']);
        if (this.map) this.drawMarkers();
    }

Update: ngOnChanges is not working, but it looks as though lapsData is being updated. In the ngOnInit is an event listener for zoom changes that also calls this.drawmarkers. When I change the zoom I do indeed see a change in markers. So the only issue is that I don't get the notification at the time the input data changes.

In the parent, I have this line. (Recall that the change is reflected in laps, but not in map).

this.rawLapsData = deletePoints(this.rawLapsData, this.selectedTps);

And note that this.rawLapsData is itself a pointer to the middle of a large json object

this.rawLapsData = this.main.data.TrainingCenterDatabase.Activities[0].Activity[0].Lap;
Aubarta answered 14/1, 2016 at 18:20 Comment(13)
Your code doesn't show how the data is updated or what type the data is. Is an new instance assigned or is just a property of the value modified?Delius
@GünterZöchbauer I added the line from the parent componentAubarta
I guess wrapping this line in zone.run(...) should do it then.Delius
Your array (reference) is not changing, so ngOnChanges() will not be called. You can use ngDoCheck() and implement your own logic to determine if the array contents have changed. lapsData is updated because it has/is a reference to the same array as rawLapsData.Zipah
@MarkRajcok this feels more like my problem as the update is triggered within angular, but I am using a deeply nested object. Is there some way of using an interim variable to create a new reference, or some otherway to signal downwards to a child?Aubarta
Well, if your code is changing rawLapsData, one option you have is to create a new array rather than modify the array contents. Then ngOnChanges() will kick in.Zipah
OK, so I have found a hack by passing another property to map that changes at the same time as rawLapsData and that triggers ngOnChanges. I know you explained it, but I still don't see how laps can pick up on the change (surely it must be using something equivalent to ngOnChanges itself?) while map can't.Aubarta
1) In the laps component your code/template loops over each entry in the lapsData array, and displays the contents, so there are Angular bindings on each piece of data that is displayed. 2) Even if Angular doesn't detect any changes (reference checking) to a component's input properties, it still (by default) checks all of the template bindings. That's how laps picks up on the changes. 3) The maps component likely doesn't have any bindings in its template to its lapsData input property, right? That would explain the difference.Zipah
OK, so it was the passing of the data further down the component tree that was saving me. Thanks - that was not entirely intuitive.Aubarta
Since the problem seems to be that the reference to the object is not changed you should make sure that your update function deletePoints returns a new object.Fabrin
laps, maps... could I see your project? sounds interestingMonecious
github.com/simonh1000/tcxeditor-ng2Aubarta
Just an info for everyone, I changed my code so that for every change i reinitialize the input var (an Array in my case) but I'm facing the same issue if I change my array to an empty Array... looks like ngOnChanges cannot detect a change of the input if it's empty/nullStinkhorn
Z
219

rawLapsData continues to point to the same array, even if you modify the contents of the array (e.g., add items, remove items, change an item).

During change detection, when Angular checks components' input properties for change, it uses (essentially) === for dirty checking. For arrays, this means the array references (only) are dirty checked. Since the rawLapsData array reference isn't changing, ngOnChanges() will not be called.

I can think of two possible solutions:

  1. Implement ngDoCheck() and perform your own change detection logic to determine if the array contents have changed. (The Lifecycle Hooks doc has an example.)

  2. Assign a new array to rawLapsData whenever you make any changes to the array contents. Then ngOnChanges() will be called because the array (reference) will appear as a change.

In your answer, you came up with another solution.

Repeating some comments here on the OP:

I still don't see how laps can pick up on the change (surely it must be using something equivalent to ngOnChanges() itself?) while map can't.

  • In the laps component your code/template loops over each entry in the lapsData array, and displays the contents, so there are Angular bindings on each piece of data that is displayed.
  • Even when Angular doesn't detect any changes to a component's input properties (using === checking), it still (by default) dirty checks all of the template bindings. When any of those change, Angular will update the DOM. That's what you are seeing.
  • The maps component likely doesn't have any bindings in its template to its lapsData input property, right? That would explain the difference.

Note that lapsData in both components and rawLapsData in the parent component all point to the same/one array. So even though Angular doesn't notice any (reference) changes to the lapsData input properties, the components "get"/see any array contents changes because they all share/reference that one array. We don't need Angular to propagate these changes, like we would with a primitive type (string, number, boolean). But with a primitive type, any change to the value would always trigger ngOnChanges() – which is something you exploit in your answer/solution.

As you probably figured out by now object input properties have the same behavior as array input properties.

Zipah answered 14/1, 2016 at 20:37 Comment(6)
Yes, I was mutating a deeply nested object, and I guess that made it hard for Angular to spot changes in the structure. Not my preference to mutate but this is translated XML and I can't afford to lose any of the surrounding data as I want to recreate the xml again at the endAubarta
@SimonH, "hard for Angular to spot changes in the structure" -- Just to be clear, Angular doesn't even look inside input properties that are arrays or objects for changes. It only looks to see if the value changed -- for objects and arrays, the value is the reference. For primitive types, the value is... the value. (I'm not sure I have all the jargon straight, but you get the idea.)Zipah
Great answer. The Angular2 team desperately needs to publish a detailed, authoritative document on change detection's internals.Howell
If I do the functionality in doCheck, in my case the do check is calling so many times. Can you please tell me any other way?Gassy
@MarkRajcok can you please help me to solve this issue #50167496Helio
can someone provide a working example? is NgDoCheck on the Child or parent component?, and once I see changes, how do I send it to grandchild element?Relational
F
42

Not the cleanest approach, but you can just clone the object each time you change the value?

   rawLapsData = Object.assign({}, rawLapsData);

I think I would prefer this approach over implementing your own ngDoCheck() but maybe someone like @GünterZöchbauer could chime in.

Fulford answered 3/7, 2017 at 15:18 Comment(2)
If you are not sure if a targeted browser would support <Object.assign()>, you can also stringify into a json string and parse back to json, which will also create a new object...Szymanowski
@Szymanowski Or a polyfill?Fulford
F
26

In .ts file (Parent component) where you are updating your rawLapsData do it like this:

rawLapsData = somevalue; // change detection will not happen

Solution:

rawLapsData = {...somevalue}; //for Object, change detection will happen

rawLapsData = [...somevalue]; //for Array, change detection will happen

and ngOnChanges will called in child component

Fruit answered 20/6, 2018 at 11:30 Comment(3)
Shoudn't it be [...somevalue] since you said it's an array?Giddings
yes, some one edited my post, i don't why, @Tim why you edited my answer wrongfully?Fruit
I didn't changed the content of your post, only edited in some formating as it was unreadable.Fellatio
R
14

As an extension to Mark Rajcok's second solution

Assign a new array to rawLapsData whenever you make any changes to the array contents. Then ngOnChanges() will be called because the array (reference) will appear as a change

you can clone the contents of the array like this:

rawLapsData = rawLapsData.slice(0);

I am mentioning this because

rawLapsData = Object.assign({}, rawLapsData);

didn't work for me. I hope this helps.

Riordan answered 29/9, 2017 at 15:12 Comment(1)
With ES6 spread operator, now you can do the same with [...rawLapsData]Giddings
P
9

If the data comes from an external library you might need to run the data upate statement within zone.run(...). Inject zone: NgZone for this. If you can run the instantiation of the external library within zone.run() already, then you might not need zone.run() later.

Perfunctory answered 14/1, 2016 at 18:28 Comment(3)
As noted in the comments to the OP, the changes were not external but deep within a json objectAubarta
As your answer says, still we need to run something for keeping thing in sync in Angular2, like angular1 it was $scope.$apply?Generality
If something is started from outside Angular, the API, patched by zone isn't used and Angular doesn't get notified about possible changes. Yes, zone.run is similar to $scope.apply.Delius
S
7

Change detection is not triggered when you change a property of an object (including nested object). One solution would be to reassign a new object reference using 'lodash' clone() function.

import * as _ from 'lodash';

this.foo = _.clone(this.foo);
Suavity answered 11/4, 2018 at 6:21 Comment(0)
B
7

I have 2 solutions to resolve your problem

  1. Use ngDoCheck to detect object data changed or not
  2. Assign object to a new memory address by object = Object.create(object) from parent component.
Balkan answered 28/11, 2018 at 4:52 Comment(1)
Would there be any notable difference between Object.create(object) versus Object.assign({}, object)?Stocker
R
5

Use ChangeDetectorRef.detectChanges() to tell Angular to run a change detection when you edit a nested object (that it misses with its dirty checking).

Repine answered 8/5, 2017 at 16:35 Comment(3)
But how ? I am trying to use this, I want to trigger changeDetection in a child after parent pushed a new item in a 2 way bounded [( Collection )].Goldman
The problem is not that change detection does not occur, but that change detection does not detect the changes ! so this does not seem to be a solution ! why did this answer got five upvotes?Nighthawk
@ShahryarSaljoughi the answer got upvotes because its one of the solutions. detectChanges() will force a re render.Lactary
G
4

I stumbled upon the same need. And I read a lot on this so, here is my copper on the subject.

If you want your change detection on push, then you would have it when you change a value of an object inside right ? And you also would have it if somehow, you remove objects.

As already said, use of changeDetectionStrategy.onPush

Say you have this component you made, with changeDetectionStrategy.onPush:

<component [collection]="myCollection"></component>

Then you'd push an item and trigger the change detection :

myCollection.push(anItem);
refresh();

or you'd remove an item and trigger the change detection :

myCollection.splice(0,1);
refresh();

or you'd change an attrbibute value for an item and trigger the change detection :

myCollection[5].attribute = 'new value';
refresh();

Content of refresh :

refresh() : void {
    this.myCollection = this.myCollection.slice();
}

The slice method returns the exact same Array, and the [ = ] sign make a new reference to it, triggering the change detection every time you need it. Easy and readable :)

Regards,

Goldman answered 4/10, 2018 at 12:49 Comment(1)
Worked for me like a charm..nice answer...thanksSallust
A
3

My 'hack' solution is

   <div class="col-sm-5">
        <laps
            [lapsData]="rawLapsData"
            [selectedTps]="selectedTps"
            (lapsHandler)="lapsHandler($event)">
        </laps>
    </div>
    <map
        [lapsData]="rawLapsData"
        [selectedTps]="selectedTps"   // <--------
        class="col-sm-7">
    </map>

selectedTps changes at the same time as rawLapsData and that gives map another chance to detect the change through a simpler object primitive type. It is NOT elegant, but it works.

Aubarta answered 14/1, 2016 at 18:58 Comment(1)
I find it hard to track all the changes on various components in template syntax, specially on mid/large scale apps. Usually I use shared event emitter and subscription to pass the data (quick solution), or implement Redux pattern (via Rx.Subject) for this (when there's time to plan) ...Elaterid
S
3

Here's a hack that just got me out of trouble with this one.

So a similar scenario to the OP - I've got a nested Angular component that needs data passed down to it, but the input points to an array, and as mentioned above, Angular doesn't see a change as it does not examine the contents of the array.

So to fix it I convert the array to a string for Angular to detect a change, and then in the nested component I split(',') the string back to an array and its happy days again.

Superhighway answered 2/10, 2016 at 22:40 Comment(3)
Yuck! The array.slice(0) approach is much cleaner.Irenairene
Happy days will be gone when you get an element with a comma ;)Giddings
I go with this for my problem, and since I was passing an object. I'll just change that to string with JSON.stringfy, JSON.parse it again in child.Simonsimona
H
1

I had to create a hack for it -

I created a Boolean Input variable and toggled it whenever array changed, which triggered change detection in the child component, hence achieving the purpose
Harpy answered 13/3, 2020 at 8:59 Comment(3)
This one is the best solution : ngDoCheck, or changeDetectionStrategy.onPush are really bad ideas,. Don't know why you need to scroll this much to actually have a descent solution.Selfacting
@IgorBeaufils actually you have to ALWAYS use changeDetectionStrategy.onPush as this is what makes your angular app more performant, but you also have to understand the consequences regarding why some particular data aren't rendering if you switch to OnPush strategy. Regarding this solution I also don't consider it to be clean because you are adding unnecessary data and complexity to the component. The accepted answer has all the explanation why Angular doesn't detect changes in an object type data and what has to be done in order to achieve the detection.Louth
@VictorMuresanu "actually you have to ALWAYS use changeDetectionStrategy.onPush as this is what makes your angular app more performant". You're right BUT in case you didn't do it from the start of the project it's not a good idea to do it only in one instance because of a bug. It's a totally other logic of angular programmation, you need to manage all side effects and there can be many.Selfacting
S
1

Not a clean solution, but you can fire the detection with:

rawLapsData = JSON.parse(JSON.stringify(rawLapsData))
Stoker answered 24/8, 2021 at 18:9 Comment(1)
Fine for small data though!Dangelo
G
0

ok so my solution for this was:

this.arrayWeNeed.DoWhatWeNeedWithThisArray();
const tempArray = [...arrayWeNeed];
this.arrayWeNeed = [];
this.arrayWeNeed = tempArray;

And this trigger me ngOnChanges

Grebe answered 6/12, 2018 at 12:28 Comment(1)
Basicly you cloned your object, so reference change.... That why ngOnChanges triggered Same as Danish Dullu response.Selfacting
U
0

In my case it was changes in object value which the ngOnChange was not capturing. A few object values are modified in response of api call. Reinitializing the object fixed the issue and caused the ngOnChange to trigger in the child component.

Something like

 this.pagingObj = new Paging(); //This line did the magic
 this.pagingObj.pageNumber = response.PageNumber;
Upswell answered 15/7, 2020 at 10:25 Comment(0)
H
0

When you are manipulating the data like:

this.data.profiles[i].icon.url = '';

Then you should use in order to detect changes:

let array = this.data.profiles.map(x => Object.assign({}, x)); // It will detect changes

Since angular ngOnchanges not be able to detect changes in array, objects then we have to assign a new reference. Works everytime!

Howdy answered 20/8, 2020 at 19:17 Comment(0)
W
0

Here's an example using IterableDiffer with ngDoCheck. IterableDiffer is especially useful if you need to track changes over time as it lets you do things like iterate over only added/changed/removed values etc.

A simple example not using all advantages of IterableDiffer, but it works and shows the principle:

export class FeedbackMessagesComponent implements DoCheck {
  @Input()
  messages: UserFeedback[] = [];
  // Example UserFeedback instance { message = 'Ooops', type = Notice }

  @HostBinding('style.display')
  display = 'none';

  private _iterableDiffer: IterableDiffer<UserFeedback>;

  constructor(private _iterableDiffers: IterableDiffers) {
    this._iterableDiffer = this._iterableDiffers.find([]).create(null);
  }

  ngDoCheck(): void {
    const changes = this._iterableDiffer.diff(this.messages);

    if (changes) {
      // Here you can do stuff like changes.forEachRemovedItem()

      // We know contents of this.messages was changed so update visibility:
      this.display = this.messages.length > 0 ? 'block' : 'none';
    }
  }
}

This will now automatically show/hide depending on myMessagesArray count:

<app-feedback-messages
  [messages]="myMessagesArray"
></app-feedback-messages>
Wigging answered 4/12, 2020 at 13:40 Comment(0)
K
0

suppose you have a nested object, like

var obj = {"parent": {"child": {....}}}

If you passed the reference of the complete object, like

[wholeObj] = "obj"

In that case, you can't detect the changes in the child objects, so to overcome this problem you can also pass the reference of the child object through another property, like

[wholeObj] = "obj" [childObj] = "obj.parent.child"

So you can also detect the changes from the child objects too.

ngOnChanges(changes: SimpleChanges) { 
    if (changes.childObj) {// your logic here}
}
Koball answered 24/1, 2021 at 17:45 Comment(0)
D
0

Simply send an object or an array in the event. NEVER send a string or number from parent to child. It will work. I had 2 child components and a parent. this is my Parent.ts : Send direct event object.

dataFrom1To2:any;
dataFrom2To1:any;
  onBallPassEventFrom1(event:any){
    this.dataFrom1To2 = event;
  }

  onBallPassEventFrom2(event:any){
    this.dataFrom2To1 = event;
  }

And parent.html is :

<div>I Am The Parent Component!</div>
<div>
    <app-child1 (ballPassEventFrom1)="onBallPassEventFrom1($event)" [datafrom2]="dataFrom2To1"></app-child1>
</div>
<div>
    <app-child2 [datafrom1]="dataFrom1To2" (ballPassEventFrom2)="onBallPassEventFrom2($event)"></app-child2>
</div>
Disserve answered 2/8, 2022 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.