首页 > 解决方案 > 错误:找不到带有路径的控件:'specs -> 2' FormArray 复选框列表

问题描述

堆栈闪电战

我正在使用反应式表单,在我的表单中,我有一个字符串数组,我用它来绑定我的复选框列表。

当我试图标记要选择的返回数组项时,在控制台中我可以看到错误

控制台中的错误消息

.ts 代码如下:

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

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

  spec = ['site-1', 'site-2', 'site-4'];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      specs: this.fb.array(['site-1', 'site-2'].map(s => this.fb.control(true)))
    });
  }
}

和html代码如下:

<form [formGroup]="form">
  <div class="col-3">
    <div class="form-group">
      <b>Select Spec Rows</b>
    </div>

    <div class="form-group overflow" formArrayName="specs">
      <div *ngFor="let site of spec; let i = index">
        <input
          type="checkbox"
          [id]="i"
          [formControlName]="i"
          [value]="site"
          (change)="specRowCheck($event,option.id, false)"
        />
        <div [innerHTML]="site"></div>
      </div>
    </div>
  </div>
</form>

ERROR Error: Cannot find control with path: 'specs -> 2'

我检查了其他问题,似乎我的 html 中缺少一些表单组,但我不确定如何应用它

标签: angularangular-reactive-forms

解决方案


您正在为缺少 formControl 设置 formControlName 指令,这就是您收到此错误的原因。由于您在 ngFor 中使用 spec 数组,它有 3 个值,在类中您只有两个 formControl 数组。

您应该有 3 个 formControl 才能与规范数组匹配。

试试这个:

this.form = this.fb.group({
      specs: this.fb.array(this.spec.map(s => this.fb.control(true)))
 });

分叉的工作示例


推荐阅读