无法读取属性' addControl'为null

时间:2018-04-22 18:42:21

标签: angular nested-forms

嵌套表单,尝试在其他表单中添加一个表单但收到错误'无法读取属性' addControl' of null'。 FormGroupDirective没有返回父'表格'它似乎。尝试应用子表单方法进行嵌套。

    <p>
      sub-forms-approach works!
    </p>
    <form [formGroup]="form">
      <!--<input formControlName="name">-->
      <app-sub-forms-approach-child-one></app-sub-forms-approach-child-one>

    </form>  
    state: {{form.status}}
    data:  {{ form.value | json}}

父组件

    import { Component, OnInit } from '@angular/core';
    import {FormBuilder, FormControl, FormGroup, Validators} from 
    '@angular/forms';

    @Component({
      selector: 'app-sub-forms-approach',
      templateUrl: './sub-forms-approach.component.html',
      styleUrls: ['./sub-forms-approach.component.css']
    })
    export class SubFormsApproachComponent implements OnInit {
    form= new FormGroup({

        });
      constructor() { 
      }
      ngOnInit() {
      }

    }

儿童表格HTML
        

          子形式 - 方法 - 儿童 - 一个工作!         

    <div formGroupName='address'>
      <input formControlName="pin">
      <input formControlName="street">
    </div>

子表单组件

    import { Component, OnInit } from '@angular/core';
    import { ControlContainer, FormGroupDirective, FormControl, FormGroup} 
     from '@angular/forms';
    @Component({
      selector: 'app-sub-forms-approach-child-one',
      templateUrl: './sub-forms-approach-child-one.component.html',
      styleUrls: ['./sub-forms-approach-child-one.component.css'],
      viewProviders: [
        {provide: ControlContainer,
          useExisting: FormGroupDirective 
        }
      ]
    })
    export class SubFormsApproachChildOneComponent implements OnInit {
      form;
      constructor(parent: FormGroupDirective) { 
        this.form = parent.form;
        console.log(parent.form);
      }

      ngOnInit() {
        this.form.addControl('address', new FormGroup({
          pin: new FormControl(),
          street: new FormControl()
        }))
      }

    }

1 个答案:

答案 0 :(得分:0)

您无法在构造函数中获取FormGroupDirective.form,因为@Input form属性尚未初始化。 Angular首先在节点创建期间实例化组件类,并且仅在初始化输入属性之后实现。

所以将代码移到ngOnInit hook:

constructor(private parent: FormGroupDirective) {}

ngOnInit() {
  this.form = this.parent.form;
  this.form.addControl('address', new FormGroup({
    pin: new FormControl(),
    street: new FormControl()
  }))
}

<强> Ng-run Example