2

I have this component:

export class MyComponent {
    @Input() active:boolean;

    constructor() {
        console.log(this.active);
    }
}

You will notice that I've declared an Input that I pass in like this:

<mycomponent
    [active]="1 == 1"></mycomponent>

When this loads, the log statement in the constructor logs undefined. What am I doing wrong?

2 Answers 2

2

@Input property bindings are first only available after the ngOnInit,

So you should do :

export class MyComponent {
    @Input() active:boolean; 

    ngOnInit() {
        console.log(this.active);
    }
}

Also FYI :

From the docs :

ngOnInit Initializes the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. Called once, after the first ngOnChanges.

More on Life Cycle Hooks

Sign up to request clarification or add additional context in comments.

2 Comments

I see. how do i use this.active to set a class, via ngClass for example? if the property is always undefined i cannot use it...
@dopatraman, it's not always undefined , it's undefined in the constructor but it's available in ngOnInit .And I didn't get your next question.
0

Below is an example of how to use this.active in your HTML template:

 <div *ngIf='active'>
   <span   [ngClass]="{'glyphicon-play': active}">
 <div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.