dopatraman
dopatraman

Reputation: 13908

How can I pass values into component?

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?

Upvotes: 2

Views: 37

Answers (2)

user6801750
user6801750

Reputation: 242

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

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

Upvotes: 0

Milad
Milad

Reputation: 28592

@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

Upvotes: 2

Related Questions