I have a local variable where the backend data is received as Array like:
itemsFromBackend: ["Item1", "Item2"]
Creating a new Array
items: FormArray
In formgroup:
ngOnInit() {
this.form = this.formBuilder.group({
items: this.formBuilder.array([ this.createItem() ])
});
}
Creating an item
createItem(): FormGroup {
return this.formBuilder.group({
name: ''
});
}
Adding an item:
addItem(): void {
this.items = this.form.get('items') as FormArray;
this.items.push(this.createItem());
}
In HTML
<div formArrayName="items" *ngFor="let item of form.get('items').controls; let i = index ">
<div *ngFor="let item of itemsFromBackEnd" [formGroupName]="i">
<input value={{item}} />
<section>
<button
mat-raised-button
color="primary"
type="button"
(click)="addItem()"
>
<i class="material-icons"> add </i>
</button>
</section>
</div>
</div>
I'm now receiving two fields with the backend values, but when I click on the add button it should display a new input field, but it is adding another two input fields with the value of backend. I need some help in displaying a new input field when I click on the add button. Thank you.