@Input property is undefined in Angular 2’s onInit

The reason you’re getting undefined in ngOnInit is because at the point where the component is initialised you haven’t actually passed in a Hero object

<my-hero-detail [hero]="selectedHero"></my-hero-detail>

At this point selectedHero has no value in your AppComponent and doesn’t until the click event on the list calls the onSelect method

Edit: Sorry realised I didn’t actually offer a fix. If you add an ngIf to my-hero-detail

<my-hero-detail *ngIf="selectedHero" [hero]="selectedHero"></my-hero-detail>

you should this will delay the initialisation of the my-hero-detail component and you should see the console output. This wont however output again when the selected hero changes.

Leave a Comment