sembilanlangit
sembilanlangit

Reputation: 355

Using @input property in child component to call service in angular 2

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?

Upvotes: 1

Views: 1616

Answers (3)

muzurB
muzurB

Reputation: 317

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

Upvotes: 4

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657741

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

Upvotes: 1

Ben Richards
Ben Richards

Reputation: 3575

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

Upvotes: 2

Related Questions