代码之家  ›  专栏  ›  技术社区  ›  JordanBarber

Angular 4 FormGroup-将父窗体控件传递给子组件

  •  0
  • JordanBarber  · 技术社区  · 6 年前

    我使用角反应形式FormGroup和FormArray。我试图将表单字段拆分为子组件,但在将父表单控件传递给子组件时遇到了问题,我觉得这应该很简单。我的父FormGroup是标题“binsForm”,我正在引用模板中的子组件,如:

    <app-child [parent]="binsForm"></app-child>
    

    然后在子组件中,我创建了一个@Input属性:

    @Input() parent: FormGroup;
    

    然后在子模板中引用该输入:

    <div class="fields-wrap" [formGroup]="parent">
       <div class="input-wrap">
          <label>Bin ID <span>*</span><input type="text" formControlName="id"></label>
       </div>
      <div class="clearfix"></div>
    </div>
    

    在以下内容中 StackBlitz ,您可以单击“编辑质量”,并在控制台中看到消息“找不到名称id为的控件”

    我遵循了此方法的教程,但不明白为什么子组件看不到表单组。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Daniel C.    6 年前

    我查看了您的代码,应用程序的子级正在等待自己的表单,而您正在尝试注入父级表单,该表单没有id、类型、子类型等子属性。

    因此,与其注入父窗体,不如尝试注入来自FormArray的子窗体( binsFormArray ),如下所示:

    <app-child [parent]="binsFormArray.at(i)"></app-child>

        2
  •  0
  •   Nadhir Falta    6 年前

    您需要在子组件上应用OnChanges以拾取新的父窗体。

    导入OnChanges。

    实施it export class ChildComponent implements OnInit, OnChanges {

    ngOnChanges(changes) {
        console.log('changes', changes);
        this.parent = changes.parent;
    }