Error: Cannot find control with path: 'specs -> 2' FormArray checkbox list
Error: Cannot find control with path: 'specs -> 2' FormArray checkbox list
我正在使用响应式表单,在我的表单中,我有一个字符串数组,我用它来绑定我的复选框列表。
当我试图标记要选择的返回数组项时,在控制台中我能够看到错误
.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 指令,这就是为什么你得到这个 error.Since 你在 ng 中使用 spec 数组因为它有 3 个值,在 class 你只有两个 formControl 数组。
您应该有 3 个 formControl 以匹配规范数组。
试试这个:
this.form = this.fb.group({
specs: this.fb.array(this.spec.map(s => this.fb.control(true)))
});
我正在使用响应式表单,在我的表单中,我有一个字符串数组,我用它来绑定我的复选框列表。
当我试图标记要选择的返回数组项时,在控制台中我能够看到错误
.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 指令,这就是为什么你得到这个 error.Since 你在 ng 中使用 spec 数组因为它有 3 个值,在 class 你只有两个 formControl 数组。
您应该有 3 个 formControl 以匹配规范数组。
试试这个:
this.form = this.fb.group({
specs: this.fb.array(this.spec.map(s => this.fb.control(true)))
});