通过引用将值从父组件传递到子组件

时间:2017-12-22 22:31:36

标签: angular pass-by-reference

我有2个组件:parentComponentchildComponent。在parentComponent我的FormGroup类型值为parentForm,通过childComponent传递给@input

export class parentComponent {
...

 parentForm: FormGroup;

....
}

export class childComponent {
...

 @Input()
 childForm :FormGroup; //The parentForm 

....
}

当我运行这些代码时,一切正常,我的childComponent会识别childForm这是parentComponent的输入值,但每当我更改parentFormparentComponent的某些属性时{1}} childComponent无法识别这些更改,当我调试代码时,我发现childComponent包含旧的输入值,并且childForm中的更改未更新在childComponent。现在我试图找到一种方法来传递parentForm的引用来解决我的问题。因为我认为通过这种方式,parentForm中的任何更改都会立即通知childForm。 我不知道怎么可能。 (Angular的版本是5.0.1)

1 个答案:

答案 0 :(得分:0)

从本质上讲,这个问题与this questionthis another question非常相关。

为了解决您的问题,我建议采用这种方法:

  • 使用带有指令NgModel的表单组填充对象。
  • 使用@Input() childForm :FormGroup
  • @Input() childForm : Object更改为NgModel对象为已填充的对象类
  • 如果Object不是原始值stringbooleannum,则会通过引用传递,以便您立即获得更新后的值。
相关问题