(角度5)错误:找不到名称为的窗体控件:

时间:2018-09-26 20:53:31

标签: angular typescript angular5 angular2-formbuilder

我正在尝试编辑表单,当我想显示要编辑的值时,使用setValue出现错误“ 错误错误:找不到名称为购买的表单控件。” < / p>

component.ts

ngOnInit() {
  this.form = new FormGroup({
      customer: new FormGroup({
        name: new FormControl(),
        lastname: new FormControl(),
        address: new FormControl(),
        phone: new FormControl()
      }),
      createdAt: new FormControl(),
      purchases: new FormArray([])
  });
}

我要编辑的功能

onEdit(invoice) {    
  this.form.setValue(invoice)   
}

component.html

<div class="col-md-8">
    <div formGroupName="customer">
      <h3>Customer</h3>
      <label>Name: <input class="form-control" type="text" formControlName="name"> </label>
      <label>Last Name:<input class="form-control" type="text" formControlName="lastname"></label>
      <label>Phone:<input class="form-control" type="text" formControlName="phone"></label>
      <label>Address:<input class="form-control" type="text" formControlName="address"></label>
   </div>
   <div><li formArrayName="purchases"></li></div>
</div>

View in StackBlitz

控制台中的值

console

1 个答案:

答案 0 :(得分:3)

该错误是由调用setValue()引起的,因为它执行严格的检查。

您正在尝试将多个项目的数组分配给在索引0仅具有一个初始FormGroup的FormArray。

在索引1上分配值失败,因为它不存在。

解决问题的步骤:

  1. 定义表单数组:

    interface MyType{
        description: string
    }
    
    @Component({
        selector: 'my-cmp',
        template: `
            <div *ngFor="let item of _list">{{item.description}}</div>
        `
    }),
    export class MyComponentList{
    
        _list: MyType[];
    
        @Input() set list( items: MyType[] ){
            if(isListValid){
                this._list = items;
            }
            this._list = [];
        }
    
        isListValid( aList: MyType[] ): boolean{
            // logic
        }
    
    }
    
  2. 使用patchValue

  3. 清除表单数组:

    purchases: new FormArray([
        new FormGroup({
            product: new FormGroup({
                categoryS: new FormControl(''),
                location: new FormControl(''),
                name: new FormControl(''),
                price: new FormControl('')
            }),
            quantity: new FormControl('')
        })
    ])
    
  4. 循环填充表单数组

    while (purchasesFormArray.length) {
       purchasesFormArray.removeAt(0);
    }
    

固定代码在这里:View in StackBlitz