@Input不工作Angular 2

Chr*_*ros 0 angular

我在设置Input属性时遇到问题.我正在试图做的是通过从app.component.ts称为值passBool并设置属性的nextComponent称为receivedBool.

这是我的代码:

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)
  }

}
Run Code Online (Sandbox Code Playgroud)

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)
    }

}
Run Code Online (Sandbox Code Playgroud)

控制台日志结果如下:

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

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

Gün*_*uer 6

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

ngOnInit()改为使用:

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

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