Just delved into learning Angular and encountered a snag. I am trying to add and remove textfields for a form, so I attempted the following code in my component.ts file:
import {FormBuilder, FormGroup, FormArray } from '@angular/forms';
This is how the import statement 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());
}
Here is the corresponding 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>
The issue arises when working with items. Especially at
addItem():
I am receiving an error stating that this is an unused method, and for
this.items = this.nameForm.get('items') as FormArray;
I encounter Type FormArray is not assignable to type any[]. Property "includes" is missing in type FormArray
Additionally, when dealing with the HTML form, I face an error indicating Identifier 'controls' is not defined
There might be an alternative approach to achieve what I intend, but currently, I am unable to figure it out.