Angular2 change detection: ngOnChanges not firing

2019-01-02 19:56发布

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 ngInit 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;

标签: angular
13条回答
闭嘴吧你
2楼-- · 2019-01-02 20:41

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,

查看更多
零度萤火
3楼-- · 2019-01-02 20:42

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);
查看更多
墨雨无痕
4楼-- · 2019-01-02 20:44

In Case of Arrays you can do it like this:

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}; //change detection will happen

and ngOnChanges will called in child component

查看更多
余生请多指教
5楼-- · 2019-01-02 20:47

ok so my solution for this was:

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

And this trigger me ngOnChanges

查看更多
只靠听说
6楼-- · 2019-01-02 20:48

I have tried all the solutions mentioned here, but for some reason ngOnChanges() still did not fire for me. So I called it with this.ngOnChanges() after calling the service that repopulates my arrays and it worked .... correct? probably not. Neat? hell no. Works? yes!

查看更多
谁念西风独自凉
7楼-- · 2019-01-02 20:53

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.
查看更多
登录 后发表回答