Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Input property is undefined in Angular 2's onInit

Tags:

angular

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?

like image 487
eesdil Avatar asked Dec 21 '15 13:12

eesdil


People also ask

Why is input undefined angular?

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.

What is @input set in angular?

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.

Are inputs available in ngOnInit?

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).


1 Answers

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.

like image 72
Zyzle Avatar answered Sep 21 '22 14:09

Zyzle