I have a question related to the following code:
Child
export class ChildComponent implements OnChanges {
public @Input() data: string[];
ngOnChanges(changes: SimpleChanges) {
console.log('I am here');
}
}
Child Template
{{ data | json }} // This is not necessary. The behaviour is the same with or without it.
<div *ngFor="let item of data">
{{ item }}
</div>
Parent
export class AppComponent implements OnInit {
public test: string[] = ['hello'];
ngOnInit() {
console.log('I am here');
}
public addItem() {
this.test.push('sample');
}
}
Parent Template
<child-component [data]="test"></child-component>
<button (click)="addItem()">Add</button>
I understand that ngOnChanges will only be called when the array reference changes and if I push an element to the array it will not be called. The following catches my attention. When I press the add button, a new element is added to the array and the view is updated correctly. I use the json pipe and an ngFor to prove that it updates correctly. If I not use json pipe, behaviour is the same. So, if the view is updated correctly, why isn't ngOnChanges called? Who is responsible for detecting that there is a change to show it in the view?
In summary, the doubt is as follows. Why when an element is added to the array the view is updated correctly but why is ngOnChanges not called?
Change detection is done differently?