2017-06-12 35 views
-1

爲什麼輸入特性在構造爲什麼輸入特性在構造函數可在組件

@Input() results: Result[]; 

constructor() { 
    console.log(this.results); // why it is not available here 
} 
+0

我認爲它在'ngOnChanges'生命週期掛鉤集。 – robbannn

+0

更多關於構造函數和OnInit的區別建立在Jonnysai [構造函數和OnInit之間的區別]的答案上(https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit) – Alex

回答

3

輸入可用未初始化財產,直到視圖設置,以便通常你可以訪問輸入值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 {} 
相關問題