从父组件到子组件的angular2中的双向数据绑定 [英] two way data binding in angular2 from parent component to child component

查看:48
本文介绍了从父组件到子组件的angular2中的双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个对象从父对象传递给子对象.在儿童中,我正在对此对象进行更改.现在,每当我在子对象中对该对象进行更改时,它都应反映在父对象中.对于前.加载子组件时:

I am passing an object from parent to child. In child I am making changes to this object. Now , whenever I am making a change to this object in child, It should reflect in parent. For ex. while loading child component :

<child [record]="record"></child>

现在,当我更改孩子中的记录时,我希望它反映在父母中.

Now when I am changing record in child.I want it to reflect in parent.

有什么办法可以做到这一点?谢谢.

any way to achieve this? thanks.

推荐答案

如果您没有在子级中重新分配 record ,则–也就是说,您并未执行 this.record = newRecord; –之类的操作.那么您所拥有的应该可以正常工作.

If you are not reassigning record in the child – i.e., you are not doing something like this.record = newRecord; – then what you have should work fine.

由于您要向子级传递JavaScript引用类型(对象),因此您对子级中对象的属性所做的任何更改–例如 this.record.property1 = someNewValue; –将会由父级看到",因为父级和子级都引用了相同的 record 对象.只有一个 record 对象正在被操作.

Since you are passing a JavaScript reference type (an object) to the child, any changes you make to the properties of the object in the child – e.g., this.record.property1 = someNewValue; – will be "seen" by the parent because both the parent and the child have a reference to the same record object. There is only one record object that is being manipulated.

如果要在子级中重新分配 record (或者如果 record 是原始类型,例如整数,字符串或布尔值),则请参见@Günter的答案.在这种情况下,涉及多个 record 对象,因此您必须告诉父级孩子何时开始使用新对象.

If you are reassigning record in the child (or if record was instead a primitive type such as an integer, string, or boolean), then see @Günter's answer. In this case, there are multiple record objects involved, so you have to tell the parent when the child starts using a new object.

这篇关于从父组件到子组件的angular2中的双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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