【问题标题】:Passing value from parent component to child component by reference通过引用将值从父组件传递到子组件
【发布时间】:2018-06-05 11:54:32
【问题描述】:

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

export class parentComponent {
...

 parentForm: FormGroup;

....
}

export class childComponent {
...

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

....
}

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

【问题讨论】:

  • stackblitz.com/edit/angular-lk4j8t :我不知道您在寻找什么行为,但我肯定也会对childForm 进行更改。看看这个stackblitz。您也可以尝试在您的childComponent 上执行this.childForm.valueChanges

标签: angular pass-by-reference


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2019-06-15
    • 1970-01-01
    • 2019-01-04
    • 2019-01-21
    相关资源
    最近更新 更多