Angular 6窗体找不到控件错误

时间:2018-11-14 06:09:48

标签: angular angular-forms angular-formbuilder

我正在尝试在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>

非常感谢!

1 个答案:

答案 0 :(得分: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>