@Input无效Angular 2

时间:2017-01-23 06:31:39

标签: angular

我在设置Input属性时遇到问题。我要做的是从app.component.ts传递一个名为 passBool 的值,并设置名为 receivedBool 的nextComponent的属性

以下是我的代码:

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

我希望你能开导我。谢谢!

1 个答案:

答案 0 :(得分:6)

执行构造函数时,输入尚不可用。

改为使用ngOnInit()

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

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