just started with learning of Angular and stacked with a problem. I want to create add/remove textfields for the form, therefore I tried the following code in my component.ts file:
import {FormBuilder, FormGroup, FormArray } from '@angular/forms';
So, this how import looks like and then
nameForm: FormGroup;
formBuilder: FormBuilder;
items: any[] = [];
createItem(): FormGroup {
return this.formBuilder.group({
name: '',
manufacture_date: ''
});
}
ngOnInit() {
this.nameForm = this.formBuilder.group({
Name: ''
items: this.formBuilder.array([ this.createItem() ])
});
}
addItem(): void {
this.items = this.nameForm.get('items') as FormArray;
this.items.push(this.createItem());
}
And here is HTML
<div formArrayName="items"
*ngFor="let item of nameForm.get('items').controls; let i = index;">
<div [formGroupName]="i">
<input formControlName="name" placeholder="Item name">
<input formControlName="price" placeholder="Item manufacture date">
</div>
Chosen name: {{ nameForm.controls.items.controls[i].controls.name.value }}
</div>
Problem is, that I got mistakes with items. Specifically here
addItem():
I recieve message, that this is unused method, and for
this.items = this.nameForm.get('items') as FormArray;
I got Type FormArray is not assignable to type any[]. Property "includes" is missing in type FormArray
And with HTML form I recieve some Identifier 'controls' is not defined
Maybe there is another way to make what I want, but for now cant see how to deal with it.