使用子组件中的@input属性以角度2调用服务

时间:2017-02-03 17:08:47

标签: javascript angular

使用角度为2的@input从父组件到子组件的通信数据。我的目的是使用值参数@input在子组件中调用service,但value属性为" undefine"。这是我的孩子组成部分:

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..


    }
}

如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

我会使用getter和setter,在setter中,你可以进行服务调用。

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

答案 1 :(得分:2)

您需要使用ngOnChanges或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;
    }
}

答案 2 :(得分:1)

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