After following a tutorial on passing async data to Angular 2 child components, specifically using solution number 2, I attempted to implement the method as shown below:
Code snippet from parent component ts :
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.networkService.getAttivitaById(this.idAttivita).subscribe((att:Attivita[]) => {
this.attivita = att[0];
})
}
Parent component html code:
<app-dettaglio-attivita [attivita]="attivita" [isModifica]="isModifica" [intervento]="intervento"></app-dettaglio-attivita>
And here is the relevant code in the child component:
@Input() attivita: Attivita;
[...]
ngOnChanges(changes: SimpleChanges) {
if(changes['attivita']){
this.initPage();
console.log("LOADED " + this.attivita.id);
}
}
Upon navigating to the page, the console output is as follows:
cannot read property 'id' of undefined
This error pertains to the line
console.log("LOADED " + this.attivita.id);
, followed by:
https://i.sstatic.net/QRbZT.png
It appears that the change event is being triggered twice. What causes these two changes? The tutorial does not address this issue. How can I prevent this error from occurring?