I try to make a dynamic form (so you can limitless add items to a list), but somehow the content of my list is not getting send because it can't find the control with path:
Cannot find control with path: 'list_items -> list_item'
My component:
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
listForm: FormGroup;
constructor(private nodeService: NodeService, private messageService: MessageService, private fb: FormBuilder,
private listService: ListService) {
this.listForm = this.fb.group({
title: ['', [Validators.required, Validators.minLength(5)]],
list_items: this.fb.array([
this.initListItem(),
])
});
}
initListItem() {
return this.fb.group({
list_item: ['']
});
}
initListItemType() {
return this.fb.group({
list_item_type: ['']
});
}
addListItem() {
const control = <FormArray>this.listForm.controls['list_items'];
control.push(this.initListItem());
}
The Template (list.component.html):
<h2>Add List </h2>
<form [formGroup]="listForm" novalidate (ngSubmit)="addList(listForm)">
<div class="form-group">
<input type="text" class="form-control" formControlName="title" placeholder="Title">
</div>
<div formArrayName="list_items">
<div *ngFor="let list_item of listForm.controls.list_items.controls; let i=index" class="panel panel-default">
{{i + 1}}.) <input type="text" formControlName="list_item" placeholder="List Item" class="form-control">
</div>
<a (click)="addListItem()">Add List Item +</a>
</div>
<button type="submit">Submit</button>
</form>
The title works just fine, but I can't find the error I have with the "formControlName", which is causing the error.
Update with what I changed list.component.html
<h2>Add List </h2>
<form [formGroup]="listForm" novalidate (ngSubmit)="addList(listForm)">
<div class="form-group">
<input type="text" class="form-control" formControlName="title" placeholder="Title">
</div>
<div formArrayName="list_items">
<div *ngFor="let list_item of listForm.controls.list_items.controls; let i=index" class="panel panel-default">
{{i + 1}}.) <input type="text" formControlName="{{i}}" placeholder="List Item" class="form-control">
</div>
<a (click)="addListItem()">Add List Item +</a>
</div>
<button type="submit">Submit</button>
</form>
And in my component I changed the constructor and my addListItem method:
listForm: FormGroup;
constructor(private nodeService: NodeService, private messageService: MessageService, private fb: FormBuilder,
private listService: ListService) {
this.listForm = this.fb.group({
title: ['', [Validators.required, Validators.minLength(5)]],
list_items: this.fb.array([
[''],
])
});
}
addListItem() {
const control = <FormArray>this.listForm.controls['list_items'];
control.push(this.fb.control(['']));
console.log(control)
}