在使用@input() 传递数据之前加载 Angular 2 子组件 [英] Angular 2 child component loads before data passed with @input()

查看:28
本文介绍了在使用@input() 传递数据之前加载 Angular 2 子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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 之前加载并且我没有定义,这是唯一的方法一个 can console.log(myData) 在 ngOnDestroy hook 中!

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.

<parent-component>
  <child-component [input]="myData" *ngIf="myData"></child-component>
</parent-component>

这篇关于在使用@input() 传递数据之前加载 Angular 2 子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆