2
votes

I kind of understand how change detection works in Angular 2 but I'm really struggling to transfer/change my AngularJS methods over to NG2 regarding change detection.

Imagine I have a component that takes a single @Input() anObject and has a single function, logAllProperties() which, for arguments sake, logs all the properties to the console. All I want to do is to call logAllProperties() every time anObject changes in anyway whatsoever.

I understand that treating the object as immutable (either with an external library like Immutable.js or by enforcing that the entire object changes even for a minor property change) will trigger ngOnChange but is there anyway to call a function whenever a change takes place aside from these or using DoCheck which I understand is potentially extremely inefficient.

As well as "is there a way", what is the correct way to do something like this? I'm new to Angular2 so I'm more than happy to learn the right way if Immutable and Observables are the way to go.

Thanks in advance

3

3 Answers

1
votes

The straightforward way of executing an action everytime anObject change is by using a setter or ngOnChange (see Fals' answer).

Using immutable objects witch a change detection strategy of OnPush is a way to improve change detection performance. This is not the most obvious use of change detection in Angular.

For a complete explanation I suggest you read this really good article and if you have some time (45 minutes) you can check this video by the author of the article here

From there, you should have a good understanding of what's going on.

0
votes

@input decorator is denoted your component is expecting to get some data from its parent which will be caught at that property

same way @output is the decorator in angular2 wherein parent component you can catch something from child.

Internally it uses observable and I don't think it's immutable.

ngrx provides a redux type immutable mechanism where every state is remembered and you can go back to them as well.

Observable and ngrx are running in parallel now.

0
votes

I found out in our projects that using set works well in some cases, but others cases that need sync between components could be troubling, then we are using ngOnChange for those cases. Here's an example.

@Input() set myProperty(myProperty: MyPropertyType) {
        if (myProperty) {
            this.logService.log(myProperty);
        }

        this._myProperty = myProperty;
}
private _myProperty: MyPropertyType= new MyPropertyType();

The thing about Angular2 new lifecycle still confuse, and the documentation samples doesn't fit most of the real world cases.