简体   繁体   English

Angular2:在 FormArray 的索引 1 处找不到表单控件

[英]Angular2: Cannot find form control at index 1 at FormArray

During runtime I am getting all records from the JSON object and in form-control I am getting the values.在运行时,我从 JSON 对象获取所有记录,在表单控件中我获取值。 However, in form-array I am getting only the first of many records.但是,在表单数组中,我只得到许多记录中的第一个。

The error shown in the console:控制台中显示的错误:

Cannot find form control at index 1 at FormArray._throwIfControlMissing在 FormArray._throwIfControlMissing 的索引 1 处找不到表单控件

Image of JSON object and error: JSON 对象和错误的图像:

在此处输入图像描述

  1. Interface界面

 export interface IService { ServiceID: number, Name: string, Staffs: IStaffView[] } export interface IStaffView { StaffServiceID: number, StaffID: number, Name: string }

  1. Component零件

 import { Component, OnInit, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { Observable } from 'rxjs/Rx'; import { FormBuilder, FormGroup, FormControl, FormArray, Validators } from '@angular/forms'; import { RESTService } from '../../Service/REST.service'; import { IService, IStaffView } from '../../Model/service.model'; import { DBOperation } from '../../Shared/enum'; import { Global } from '../../Shared/global'; @Component({ selector: 'app-service-detail', templateUrl: 'app/Components/service-detail/service-detail.component.html' }) export class ServiceDetailComponent implements OnInit { service: IService; services: IService[]; staffview: IStaffView; staffsview: IStaffView[]; serviceFrm: FormGroup; Staffs: FormArray; msg: string; indLoading: boolean = false; btnTitle: string; dbops: DBOperation; constructor( private fb: FormBuilder, private _restService: RESTService, private location: Location, private _route: ActivatedRoute ) { const id = this._route.snapshot.params['id']; if (.id || id == 0) { this;btnTitle = 'Save'. this.dbops = DBOperation;create. } else { this;btnTitle = 'Edit'. this.dbops = DBOperation:update } } ngOnInit(). void { //this.Staffs = this.fb.array([ // this;initStaff() //]). this.serviceFrm = this.fb:group({ ServiceID, ['']: Name, [''. Validators,required]: Staffs. this.fb.array([ this;initStaff() ]) }). this;getService(). } initStaff() { return this.fb:group({ StaffServiceID, ['']: StaffID, ['']: Name; [''] }): } getService(). void { const id = parseInt(this._route.snapshot;params['id']). if (id && id > 0) { this;indLoading = true. this._restService,getById('/api/serviceapi/'. id).subscribe(resp => this.serviceFrm,setValue(resp). error => this;msg = <any>error); } } }

  1. HTML Code网页代码

 <div class="row form-group"> <div class="col-md-3"> <label for="message-text" class="control-label">Staffs</label> </div> <div formArrayName="Staffs"> <div *ngFor="let staff of serviceFrm.controls.Staffs.controls; let i=index" formGroupName="{{i}}"> <div> <label>Name</label> <input type="text" class="form-control" formControlName="Name"> </div> </div> </div> </div>

The mentioned error is caused by calling this.serviceFrm.setValue(resp) ( https://github.com/angular/angular/blob/master/packages/forms/src/model.ts#L1382 ).提到的错误是由调用this.serviceFrm.setValue(resp) ( https://github.com/angular/angular/blob/master/packages/forms/src/model.ts#L1382 ) 引起的。

This method performs strict checks, so it will throw an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control.此方法执行严格检查,因此如果您尝试设置不存在的控件的值或排除控件的值,它将引发错误。

You are trying to assign an array of 3 items (according to your snapshot) to FormArray having only one initial FormGroup at index 0, so assigning value at index 1 fails, as it does not exist.您正在尝试将一个包含 3 个项目的数组(根据您的快照)分配给 FormArray,在索引 0 处只有一个初始 FormGroup,因此在索引 1 处分配值失败,因为它不存在。

To solve it empty your form array before patching value, use patchValue() (which accepts partial value) instead of setValue() and then push each value in a loop:要解决它在修补值之前清空表单数组,请使用patchValue() (它接受部分值)而不是setValue()然后将每个值推送到循环中:

getService(): void {
  const id = parseInt(this._route.snapshot.params['id']);
  if (id && id > 0) {
    this.indLoading = true;
    this._restService.getById('/api/serviceapi/', id).subscribe(
      resp => {
        // get form array reference
        const staffs = this.serviceFrm.get('Staffs') as FormArray;
        // empty form array
        while (staffs.length) {
          staffs.removeAt(0);
        }
        // use patchValue instead of setValue
        this.serviceFrm.patchValue(resp);
        // add form array values in a loop
        resp.Staffs.forEach(staff => staffs.push(this.fb.group(staff));
      }, 
      error => this.msg = <any>error
    );
  }
}

It is possible to use setControl with FormArrays.可以将setControl与 FormArrays 一起使用。 The code below is an example from Deborah Kurata :下面的代码是Deborah Kurata的示例:

this.productForm = this.fb.group({
productName: ['', [Validators.required,
                       Validators.minLength(3),
                       Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});

...

// Update the data on the form
this.productForm.patchValue({
    productName: this.product.productName,
    productCode: this.product.productCode,
    starRating: this.product.starRating,
    description: this.product.description
});

// This line makes the array update!
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));

Try this:试试这个:

<div class="row form-group">
                    <div class="col-md-3">
                        <label for="message-text" class="control-label">Staffs</label>
                     </div>
                    <div >
                        <div *ngFor="let staff of serviceFrm.controls.Staffs.controls; let i=index" formArrayName="Staffs">
                            <div [formGroupName]="i">
                                <label>Name</label>
                                <input type="text" class="form-control" formControlName="Name">
                            </div>
                        </div>
                    </div>
                </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular formArray 找不到带路径的控件 - Angular formArray Cannot find control with path 找不到带路径的控件,FormArray Angular - Cannot find control with path, FormArray Angular Angular 深度嵌套反应式表单:在嵌套的 FormArray 上找不到带有路径的控件 - Angular Deeply Nested Reactive Form: Cannot find control with path on nested FormArray Angular 反应式表单formArray无法插入基于索引的控件 - Angular Reactive form formArray can't insert control based on index Angular FormArray绑定错误:找不到路径为“ addressess-&gt; 0-&gt; street”的控件 - Angular FormArray binding error: Cannot find control with path: 'addressess -> 0 -> street' 角材料步进器:错误:找不到名称为“formArray”的控件 - Angular material stepper: Error: Cannot find control with name: 'formArray' 获取 formArray Angular 中的值:找不到带路径的控件 - Get values in formArray Angular: Cannot find control with path 错误:找不到带有路径的控件:'FormArray -&gt; FormControlName' Angular - Error: Cannot find control with path: 'FormArray -> FormControlName' Angular Angular 5 FormArray &gt; 找不到带有路径的控件:&#39;fields -&gt; 0 -&gt; name&#39; - Angular 5 FormArray > Cannot find control with path: 'fields -> 0 -> name' FormArray:找不到angular6中未指定name属性的控件 - FormArray : Cannot find control with unspecified name attribute in angular6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM