1

Communication data from parent component to child component using @input in angular 2. My purpose is I want to call service in child component using value parameter @input, but the value property is "undefine". this is my child component :

import { Component, OnInit,  EventEmitter, Input,Output } from     '@angular/core';

@Component({
    selector: 'app-child', 
    templateUrl: './child.component.html'
})

export class ChildComponent  implements OnInit {


    @Input() productId: any; --> working perfectly if bind into html

    constructor() {

    }

    ngOnInit(): void {
        console.log(this.productId) --> undefine?
    //in this methode i will call service to fetch another data from database using parameter productId..


    }
}

How to solve this?

4
  • Why do you think it should be defined? Where does productId come from? Commented Feb 3, 2017 at 17:13
  • from parent component, your answer is perfect @GünterZöchbauer Commented Feb 3, 2017 at 17:32
  • If you fetch it from a server then it's not yet available when ngOnInit() is called. A setter or ngOnChanges also works for data that is set later. ngOnInit() only works for data that is already available when the component is created. Commented Feb 3, 2017 at 17:33
  • thank you very much @GünterZöchbauer Commented Feb 3, 2017 at 17:36

3 Answers 3

4

I would use a getter and setter and inside the setter, you would make your service call.

// Declare a private underlying variable for the getter and setter
private _productId: any;
@Input()
set productId(id: any){
    this._productId = id;
    // Make your service call here
}
get productId(){
    return this._productId;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear! If this solves your issue, could you please mark the answer as accepted? Happy coding!
2

You need to use either ngOnChanges or ngAfterViewInit:

export class ChildComponent  implements OnChanges {
    // Subscribe to the change event and update the model
    ngOnChanges(changes: {[propName: string]: SimpleChange}) {
        let key = 'Data';
        this.productId = changes[key].currentValue;
    }
}

Comments

1
@Input() 
set productId(value: any) {
  console.log(value);
}

1 Comment

This is sufficient if all you need is to perform an action inside the setter and if you do not actually use the productId anywhere else. But if you need to access this variable, then you need to implement a getter as well and have a "backing field".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.