2
votes

How to capture the @Input() parameter in the child component controller class. I tried to console log it from Constructor and OnInit life cycle event, but it comes as undefined. But id gets properly displayed on the child component html with one way binding

I needed the parameter info to write some custom logic in my child component.

parent.component.ts

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {
    parameter : any = [1 ,2, 3] ; 
}

child.component.ts

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {
    @Input() parameter : any ; 
    Constructor() {
        console.log(this.parameter) // prints undefined
    }
    ngOnInit() {
        console.log(this.parameter) // prints undefined
    }
}

parent.component.html

<app-child [parameter]='parameter' ></app-child>

child.component.html

{{ parameter }} // prints [1 ,2, 3]
3
add some example codeKamil Kiełczewski

3 Answers

3
votes

If you see in this plunker of your code you will see that only constructor outputs undefined and ngOnInit outputs the array [1, 2, 3]

Here is a working plunker https://embed.plnkr.co/szRxO7b94r1o15vLbLbl/

Update for comment The plunker now uses a service and a test API and it works fine on parent and child. Uses ngOnChanges so you can work with the response once it's returned. You should read the lifecycle hooks like @Günter Zöchbauer mentions in his answer.

2
votes

@Input()s are not yet set when the constructor is executed.

When change detection runs and updates @Input()s ngOnChanges() is called.

After ngOnChanges() was called the first time, ngOnInit() is called.

For more details about lifecycle methods see https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

0
votes

As people say before you should get parameter values in ngOnInit()

And two details: you don't need use 'implements OnInit', and write ' constructor()' using small 'c' letter at the beginning.