angular - 错误:找不到带有路径的控件:'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 中缺少一些表单组,但我不确定如何应用它
解决方案
您正在为缺少 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)))
});
推荐阅读
- php - 如何在 Wordpress 的另一个函数和插件中访问变量
- javascript - 为什么第二个反向引用不起作用?
- sql - 一般错误;383 无效标识符:RESB:内部连接
- algolia - 如何在分层菜单中显示不同的计数?
- r - 正则表达式从列表中查找单词,当特定单词之前没有出现 3 个单词时
- r - 按时间段绘制 R 中的唯一组
- html - 如何仅使用 CSS 创建带正方形的网格,同时尊重最大宽度和高度?
- arangodb - 使用 ArangoDB java 驱动程序批量导入图形数据
- java - Java 流映射中可重用的单实例包装器/对象
- mysql - MySQL:为什么我会得到“错误代码:1054。'字段列表'中的未知列'SLI_nuevo.id_oc'?