Usr
Usr

Reputation: 2838

Pass async data to child component with ngOnChanges does not work

Following this tutorial, precisely solution n 2, I've tried to pass async data to child component this way:

Parent component ts :

ngOnInit() {
    this.route.queryParams.subscribe(params => { 
   this.networkService.getAttivitaById(this.idAttivita).subscribe((att:Attivita[]) => {
          this.attivita = att[0];
        })
  }

Parent component html:

<app-dettaglio-attivita [attivita]="attivita" [isModifica]="isModifica" [intervento]="intervento"></app-dettaglio-attivita>

And then child component:

@Input() attivita: Attivita;
[...]

ngOnChanges(changes: SimpleChanges) {
    if(changes['attivita']){
      this.initPage();
      console.log("LOADED " + this.attivita.id);
    }
  }

When I go to the page, in console it is printed, in order:

cannot read property 'id' of undefined

referring to the line console.log("LOADED " + this.attivita.id); and right after I have:

enter image description here

It seems to catch two times the change. But what are the two changes? In the tutorial there's no word about this. How can I handle this without having the error?

Upvotes: 0

Views: 302

Answers (1)

ssuperczynski
ssuperczynski

Reputation: 3416

You need to check if currentValue exists es well.

ngOnChanges(changes: SimpleChanges) {
    const { attivita } = changes;
    if (attivita && attivita.currentValue) {
      this.initPage();
      console.log("LOADED " + this.attivita.id);
    }
}

Upvotes: 2

Related Questions