Trying to get the component's @Input
value in constructor
or ngOnInit
. But it is coming as undefined
all the time.
I updated the hero plunker with console.log
to show the issue (beta angular). http://plnkr.co/edit/dseNM7OTFi1VNG2Z4Oj5?p=preview
export class HeroDetailComponent implements OnInit { constructor(){ console.log('hero', this.hero) } public hero: Hero; ngOnInit() { console.log('hero', this.hero) } }
What am I doing wrong here?
Why is it undefined? Answer: because the view isn't initialized yet. That's why you should avoid referencing component-level objects in the constructor. Instead, move that same code to the ngOnInit() method.
Use the @Input() decorator in a child component or directive to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component.
Input properties are populated before ngOnInit() is called. However, this assumes the parent property that feeds the input property is already populated when the child component is created. In your scenario, this is not the case – the images data is being populated asynchronously from a service (hence an http request).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With