2017-01-23 123 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你的评论应该指出什么? –

相关问题