2017-01-23 97 views
0

我在設置Input屬性時遇到問題。我想要做的是傳遞app.component.ts中的值passBool並設置屬性的下一個組件稱爲receivedBool@Input不工作Angular 2

這裏是我的代碼:

app.component.ts

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <nextComponent [receivedBool]="passBool"></nextComponent> 
    ` 
}) 

export class AppComponent { 

    //Variables 
    passBool: Boolean = true; 

    constructor(){ 
    console.log('The boolean value we are trying to pass is: ' + this.passBool) 
    } 

} 

nextComponent.component.ts

import { Component, Input } from '@angular/core'; 

@Component({ 
    selector: 'nextComponent', 
    template: `<i> </i> ` 
}) 

export class NextComponent { 

    @Input() receivedBool: Boolean = false; 

    constructor() { 
     console.log('The boolen value we are receiving here is: ' + this.receivedBool) 
    } 

} 

控制檯日誌的結果是:

The boolean value we are trying to pass is: true - app.component.ts

The boolean value we are receiving here is: false - nextComponent.component.ts

我希望你能賜教。謝謝!

回答

6

執行構造函數時輸入還不可用。

使用ngOnInit()代替:

export class NextComponent { 
    @Input() receivedBool: Boolean = false; 

    ngOnInit() { 
     console.log('The boolen value we are receiving here is: ' + this.receivedBool) 
    } 
} 
+0

謝謝你,幫我想通休息了! –

+0

角度在運行時只讀取屬性值只在編譯時,檢查此答案https://stackoverflow.com/questions/39614451/angular-2-input-binding-does-not-work/39614592#39614592 – kelgwiin

+0

@kelgwiin你的評論應該指出什麼? –