无法读取 null 的 属性 'addControl'

Cannot read property 'addControl' of null

嵌套表单,试图将一个表单添加到另一个表单中,但出现错误“无法读取 属性 'addControl' of null”。 FormGroupDirective 似乎没有返回父 'form'。尝试应用子表单方法进行嵌套。

    <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

sub-forms-approach-child-one 作品!

    <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()
        }))
      }

    }

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

所以将您的代码移动到 ngOnInit 钩子:

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

我在使用不带包装形式组的输入 属性 formControlName="mainForm" 时出现了同样的错误