During construction, the @Input value is not yet set. How can Angular2 set the @Input value before the component was actually constructed?
You need to wait for the component to initialize; which means all @Input values @Input set. You can do this by implementing the OnInit interface.
So, to fix your example:
<log-user [user]="user"></log-user>
(Note: user must be a specific object, otherwise in this example, undefined will still be registered. You can add *ngIf="user" to the html log-user tag to ensure that the tag does not get rendered until user actually exists. )
make:
import {Component, Input, OnInit} from 'angular2/core'; @Component({ selector: 'log-user', template: `This works: {{user}}` }) export class LogUserComponent implements OnInit { @Input() user:any; ngOnInit() {
You can also simply create the ngOnInit method on your component without implementing an interface, but by importing the OnInit interface that you provide with the Typescript compiler, avoid typographical errors.
Angular docs about OnInit :
Implement this interface to execute custom initialization logic after your data properties associated with the directive have been initialized.
ngOnInit is called immediately after the data properties associated with the directive were checked for the first time and before any of its children were checked. It is called only once when the directive is instantiated.
source share