我有一个看起来像这样的子组件
子组件
@Component({
selector: 'child-component',
//TemplateUrl, Styles and Providers
})
export Class ChildComponent implements OnInit{
@Input()
arrayToGet; //An array that I want to pass from Parent to child
ngOnInit(){
console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
}
//A bunch of methods to work with the array I get
}
父组件
@Component({
selector: 'parent-component',
template: '<div>
<child-component [arrayToGet]="models"></child-component>
</div>',
//A bunch of Styles and Providers
})
export class ParentComponent{
models;
constructor(......){}
ngOnInit(){
//Get an array from a service assign to this.models;
}
}
问题是我无法对 ChildComponent
内的 arrayToGet
执行任何操作。不过,我可以在 ChildComponent
的 HTML 中使用 arrayToGet
上的属性。
有什么想法吗?
最佳答案
每当尝试使用 @Input
装饰器将数据从 parent
传递到 child
时,并且传递数据在 时不可用child
初始化,最好使用 setter
,而不是直接绑定(bind)到 child
组件中的变量。每当父组件中的数据更新时,使用 setter
将更新子组件 vairable。
export Class ChildComponent implements OnInit{
arrayToGet; //An array that I want to pass from Parent to child
ngOnInit(){
console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
}
@Input('arrayToGet')
set _arrayToGet(data: Array) {
this.arrayToGet = data;
console.log(this.arrayToGet);
}
//A bunch of methods to work with the array I get
}
关于angular - 使用 @Input 装饰器访问传递的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46138267/