使用 Angular 2中的@input从父组件到子组件的通信数据。我的目的是我想使用值参数@input在子组件中调用服务,但值属性是“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..
}
}
如何解决?
最佳答案
我会使用 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;
}
关于javascript - 在子组件中使用@input 属性以 Angular 2 调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42029446/