Angular 2子组件在通过@input()传递数据之前加载 [英] Angular 2 child component loads before data passed with @input()
问题描述
在我的angular 2应用程序中,有两个组件:组件A(父级)和组件B(子级).
I have two component in my angular 2 application : component A (parent) and component B (child).
当我使用@Input()将数据(myData)从A传递到B时,我将数据存储在我的B(子组件)中,但是问题是子组件在myData之前加载并且我未定义,这是唯一的方法一个可以console.log(myData)在ngOnDestroy挂钩中!
When i passe data (myData) from A to B with @Input() i get my data in my B (child component), but the problem is that the child component loads BEFORE myData and i got indefined, the only way a can console.log(myData) is in ngOnDestroy hook !
如何处理这种装载指令?
How to deal with this kind of load order ?
推荐答案
这是对我来说最简单的解决方案.在父组件中使用 * ngIf
延迟子组件的初始化.仅当 myData
具有值时,才绑定子组件.
Here is a solution that was easiest for me. Use *ngIf
in your parent component to delay the initialization of the child component. You will bind the child component only if myData
has a value.
让我知道代码示例是否有帮助,我可以将一些内容放在一起.希望这可以帮助.干杯!
Let me know if a code example would help and I can put something together. Hope this helps. Cheers!
这篇关于Angular 2子组件在通过@input()传递数据之前加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!