为什么组件上的输入属性在构造函数中不可用

ale*_*n96 0 angular

为什么组件上的输入属性在构造函数中不可用

@Input() results: Result[];

constructor() {
   console.log(this.results); // why it is not available here 
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*oot 7

在设置视图之前,不会初始化输入属性,因此通常可以访问ngOnInit()上的输入值

检查LifeCycle. https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

import {Component, Input} from 'angular2/angular2'

@Component({
  selector: 'child',
  template: `   
    <p>The next number is {{ mynumber + 1 }}</p>
  `
})
class ChildComponent {
  @Input() mynumber: number;
    ngOnInit(){
         console.log(this.number);
   }
}

@Component({
  selector: 'parent',
  template: `
    <child [mynumber]="41"></child>
  `
})
export class ParentComponent {}
Run Code Online (Sandbox Code Playgroud)