0

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

为什么我会收到此错误:

错误:找不到名称为“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>

非常感激!

4

1 回答 1

1

我试图用stackblitz重现你的错误,发现你必须修改代码才能完成你想要的,以我最好的理解。请检查链接代码现在不会在控制台中引发任何错误。

修改后的代码如下:

  /// 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>
于 2018-11-14T06:58:45.850 回答