Take a look at this code snippet
import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core'
@Component({
selector: 'child1',
template: `
<div>reference change for entire object: {{my_obj1.name}}</div>
<div>reassign primitive in property of object: {{my_obj2.name}}</div>
<div>update primitive in property of object: {{my_obj2.num}}</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Child1 {
@Input()
my_obj1: Object = {'name': ''};
@Input()
my_obj2: Object = {'name': '', 'num': 0};
ngDoCheck() {
console.log('check from child1');
console.log(this.my_obj1);
console.log(this.my_obj2);
}
}
@Component({
selector: 'parent',
template: `
<div>
<child1
[my_obj1]="my_obj1"
[my_obj2]="my_obj2"
>
</child1>
<button (click)="change_obj1()">
Change obj1
</button>
</div>
`,
directives: [Child1]
})
export class App {
my_obj1: Object = {'name': 'name1'};
my_obj2: Object = {'name': 'name2', 'num': 0};
change_obj1() {
this.my_obj1 = {'name': 'change1'}
this.my_obj2['name'] = 'change2';
this.my_obj2['num'] += 1;
}
}
After conducting an experiment, I have come to understand the current change detection strategy in Angular2. Can someone confirm if my understanding is accurate?
By default, Angular2 checks for value equality during change detection. Without
ChangeDetectionStrategy.OnPush
, every watched variable in the component tree undergoes a check for value equality. If there is a mismatch, that specific component will be re-rendered, otherwise it will not.When implementing
ChangeDetectionStrategy.OnPush
in a component, the behavior changes as follows:i. If there is a reference change within the component, it triggers a re-render and initiates change detection in child components based on the specific algorithm defined by
ChangeDetectionStrategy.OnPush
.ii. If there is no reference change within the component, no re-render occurs, and change detection is skipped in child components, regardless of the presence of
ChangeDetectionStrategy.OnPush
.
Is this interpretation correct?