0

I 'm having a problem setting an Input property. What I'm trying to do is pass a value from app.component.ts called passBool and set the property of the nextComponent called receivedBool.

Here are my codes:

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

}

Console log results are:

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

I hope you could enlighten me. Thanks!

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

1 Answers1

7

Inputs are not yet available when the constructor is executed.

Use ngOnInit() instead:

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

    ngOnInit () {
        console.log('The boolen value  we are receiving here is: ' + this.receivedBool)
    }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you, this helped me figured the rest out! – Chris Javier Oliveros Jan 23 '17 at 06:39
  • The angular does not read attribute value during runtime only during compiling time, check this answer https://stackoverflow.com/questions/39614451/angular-2-input-binding-does-not-work/39614592#39614592 – kelgwiin Jun 06 '17 at 18:08
  • @GünterZöchbauer When you call the component initially when it's compiling it does not have value until runtime, in a interval you have empty value, according to the explanation. – kelgwiin Jun 07 '17 at 18:41
  • You don't call a component when it's compiling. Compiling is before the browser loads the component. – Günter Zöchbauer Jun 07 '17 at 19:58