Search code examples
angulartypescriptparent-childangular-componentsangular7

Passing asynchronous value from parent to child component with @Input


I am trying to pass a map, which come from an api, from parent to child component, in angular 7.

parent.ts:

export class AppComponent {
  title = 'taurs-frontend';
  categories: any;
  isLoggedIn = false;

ngOnInit(){
    this.roomDataService.getData(`${environment.api_url}/api/Categories`)
    .subscribe(categories => {
      this.categories=categories
    }); 
  }

parent.html:

 <app-room-card [categories]="categories"></app-room-card> 

child.ts:

@Component({
  selector: 'app-room-card',
  templateUrl: './room-card.component.html',
  styleUrls: ['./room-card.component.css']
})
export class RoomCardComponent implements OnInit {
    @Input('categories') catname: any;

    ngOnInit() {
        console.log('aaa'+ this.catname);
    }
// ..
}

When I try to log the variable catname, it is undefined. If I try to import variable title from the parent, everything works properly. How can I pass categories to the child, filling it with the values from the API call?


Solution

  • You are trying to pass asynchronous data to child component. You have different solutions to do that. For exemple, you can use ngOnChanges instead of ngOnInit:

    ngOnChanges() {
        console.log('aaa'+ this.catname);
    }
    

    Another solution is to use *ngIf, in order to delay the initialization of posts components:

    <app-room-card *ngIf="categories" [categories]="categories"></app-room-card>
    

    Take a look at this link: https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components#toc-solution-2-use-ngonchanges