I am using reactive forms and in my forms I have an array of string with which I bind my checkbox list.
When I a trying to mark the returned array items to be selected, In console I am able to see the error
.ts code as follow :
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)))
});
}
}
and html code as follow :
<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'
I checked other questions and its seems I am missing some form group in my html but I am not sure how to apply that
You are setting formControlName directive for missing formControl that's why you getting this error.Since you using spec array in ngFor it have 3 value, in class you have only two array of formControl.
You should have 3 formControl inorder to match with spec array.
Try this:
this.form = this.fb.group({
specs: this.fb.array(this.spec.map(s => this.fb.control(true)))
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments