On construction time the @Input value is not yet set. How could Angular2 set the @Input value before the component was actually constructed?
You have to wait for the component to be initialized; meaning all @Input values have been set. You can do so by implementing the OnInit interface.
So to fix your example:
<log-user [user]="user"></log-user>
(Note: user must be a defined object, otherwise in this example undefined would still be logged. You can add *ngIf="user" to the log-user html tag to ensure the tag does not get rendered before user actually exists.)
Do:
import {Component, Input, OnInit} from 'angular2/core';
@Component({
selector: 'log-user',
template: `This works: {{user}}`
})
export class LogUserComponent implements OnInit {
@Input() user:any;
ngOnInit() {
// this now gets logged as 'user'
console.log(this.user);
}
}
You can also just create the ngOnInit method on your component without implementing the interface, but by importing the OnInit interface you are ensured by the Typescript compiler not make a typo mistake.
The Angular docs about OnInit states:
Implement this interface to execute custom initialization logic after
your directive's data-bound properties have been initialized.
ngOnInit is called right after the directive's data-bound properties
have been checked for the first time, and before any of its children
have been checked. It is invoked only once when the directive is
instantiated.