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

问题描述 投票:1回答:1

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

export class parentComponent {
...

 parentForm: FormGroup;

....
}

export class childComponent {
...

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

....
}

当我运行这些代码一切都很好,我的childComponent识别childForm这是parentComponent的输入值,但每当我在parentForm中更改parentComponent中的某些属性时,childComponent无法知道这些变化,当我调试我的代码时,我看到childComponent拥有旧的输入值,并且在childFormchildComponent中没有更新变化。现在我试图找到一种方法来传递parentForm的参考来解决我的问题。因为我认为通过这种方式,parentForm的任何变化都会立即通知childForm。我不知道怎么可能。 (Angular的版本是5.0.1)

angular pass-by-reference
1个回答
0
投票

从本质上讲,这个问题与this questionthis another question有很大关系。

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

  • 使用带有指令NgModel的表单组填充对象。
  • 使用@Input() childForm :FormGroup@Input() childForm : Object更改为NgModel作为对象填充对象类
  • 如果Object不是原始值stringbooleannum,它将通过引用传递,因此您将立即获得更新的值。
© www.soinside.com 2019 - 2024. All rights reserved.