Reputation: 540
My component has an mutable object input. When property of object changed,ngOnChanges
of component is not called.It's easily understand.But the it's display changed rightly.
My component hero-card
:
export class HeroCardComponent implements OnChanges , DoCheck {
@Input()
Hero: Hero;
@Input()
Title: string;
ngOnChanges(changes: SimpleChanges) {
for (const propName in changes) {
const chng = changes[propName];
const cur = JSON.stringify(chng.currentValue);
const prev = JSON.stringify(chng.previousValue);
console.log(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
}
}
}
It's template:
{{Title}}<br>
Hero title : {{Hero.title}}<br>
Hero name : {{Hero.name}}<br>
I changed hero.name in an input which has an two-way binding with hero.name.
Could Angular really checked the change?
The display changed seems it checked the change even in mutable object.Yeah , great!
But ngOnChanges
is not called. It seemed that angular not checked the change. May be it only reset all of the view no matter change or not.
Who can tell me the truth?Thanks!
Upvotes: 3
Views: 555
Reputation: 105439
Angular tracks input bindings by reference, and since the reference to Hero
object hasn't changed ngOnChanges
is not triggered. It means that Angular hasn't detected change for the Hero
object reference. And this check for changes is actually performed when Angular checks parent component, not HeroCardComponent
.
However, in template you use the following:
Hero name : {{Hero.name}}<br>
which means that everytime Angular runs change detection for the HeroCardComponent
component it has to check whether Hero.name
is changed. It is not related really related to the check of Hero
object reference. I happens when Angular runs change detection for the HeroCardComponent
component. If the expression used in DOM evaluates to a different value, it updates the dom. You can read more about updating the DOM in the The mechanics of DOM updates in Angular.
If you want to track object mutations yourself you can use ngDoCheck lifecycle hook. It's explained in depth in the article If you think ngDoCheck
means your component is being checked — read this article.
For more information on change detection you should read:
Upvotes: 3