Angular 6 Forms Cannot find control 错误

Angular 6 Forms Cannot find control error

我正在尝试在 Angular 中构建表单数组。当数据没有出现时,我将代码最小化以显示行为。我必须为最终代码使用表单数组。请帮助我度过难关。我正在使用 Angular 6.

为什么我会收到此错误:

Error: Cannot find control with name: 'resultOptions'

// My component .ts file

import {FormControl, FormArray, FormBuilder, FormGroup} from '@angular/forms';
export class MyComponent implements OnInit, OnDestroy  {

  private resultForm: FormGroup;
  private destroyed$: Subject<boolean> = new Subject();

  resultData = [
    {
      text: 'My Text',
    }];

  constructor(private formBuilder: FormBuilder) {

    this.resultForm = this.formBuilder.group({
      childData: this.formBuilder.array([])
    });

    this.setMainOptions();
  }

  setMainOptions() {
    const control = <FormArray>this.resultForm.controls.childData;
    this.resultData.forEach(x => {
      control.push(this.formBuilder.group({
        text: new FormControl()}))
    })
  }
  ngOnInit() {
  }

  ngOnDestroy() {
    this.destroyed$.complete();
  }
}

// my html

    <form [formGroup]="resultForm">
<div formArrayName="resultOptions">
  <div *ngFor="let mainOption of resultForm.get('childData').controls; let i=index">
    <div [formGroupName]="i">
      <input [formControlName]="text" />
    </div>
  </div>
</div>
</form>

<pre>{{resultForm.value | json}}</pre>

非常感谢!

我尝试用 stackblitz 重现您的错误,发现您必须修改代码才能完成您想要的,据我所知。请检查 link 代码现在不会在控制台中抛出任何错误。

修改后的代码如下:

  /// Component 

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

  @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
  })
  export class AppComponent  implements OnInit, OnDestroy  {

    private resultForm: FormGroup;
    // private destroyed$: Subject<boolean> = new Subject();

    resultData = [
      {
        text: 'My Text 1',
      },
      {
        text: 'My Text 2',
      },
      {
        text: 'My Text 3',
      },
      {
        text: 'My Text 4',
      }];

    constructor(private formBuilder: FormBuilder) {

      this.resultForm = this.formBuilder.group({
        childData: this.formBuilder.array([])
      });

      this.setMainOptions();
    }

    setMainOptions() {
      const control = <FormArray>this.resultForm.controls.childData;
      this.resultData.forEach(x => {
        control.push( new FormControl(x.text))
      })
    }

    ngOnInit() {
    }

    ngOnDestroy() {
      // this.destroyed$.complete();
    }
  }

\\ HTML
<form [formGroup]="resultForm">
<div formArrayName="childData">
  <ng-container> 
  <div *ngFor="let mainOption of resultForm.get('childData').controls; let i=index">
      <input formControlName='{{i}}' />
  </div>
  </ng-container>
</div>
</form>

{{resultForm.get('childData').controls.length}}

<pre>{{resultForm.value | json}}</pre>