Consider the following code
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;
}
}
From the experiment I made, here is my understanding of the current Angular2
change detection strategy, can someone verify it if its true?
Angular2 by default checks for value equality when doing change detection. If there are no
ChangeDetectionStrategy.OnPush
, every watched variable in component tree is checked for value equality. If value equality is false, that specific component will be rerender, and if value equality if true, that specific component will not be rerender.If you add
ChangeDetectionStrategy.OnPush
to a component. The behavior changes as followsi. If variable inside the component have reference change, the component is rerendered, and child component is checked for change detection (its specific change detection algorithm value/reference check depends on
ChangeDetectionStrategy.OnPush
)ii. If variable inside the component don't have reference change, the component is not rerendered, and child component is not checked for change detection, regardless of presence of
ChangeDetectionStrategy.OnPush
Is this the correct interpretation?