@Input Angular 2 不起作用



我在设置输入属性时遇到问题。我正在尝试做的是从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

我希望你能启发我。谢谢!

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

请改用ngOnInit()

export class NextComponent {
    @Input() receivedBool: Boolean = false;
    ngOnInit () {
        console.log('The boolen value  we are receiving here is: ' + this.receivedBool)
    }
}

最新更新