It's more easy if you first think about the data you get. I think you get some like
[{filename:..,agenda:[
{sheetNumber:..,title:...,description...},
{sheetNumber:..,title:...,description...}
...
]
},
{filename:..,agenda:[
{sheetNumber:..,title:...,description...},
{sheetNumber:..,title:...,description...}
...
]
}
....
]
You see that you has an FormArray, (a series of FormGroup) that has two properties, "filename" and "agenda" (Agenda is a new FormArray)
declare a variable as formArray
form: FormArray
And create two functions.
createItemData(data):FormGroup
{
data=data|| {} as dataI;
return new FormGroup(
{
filename:new FormControl(data.filename),
agenda:new FormArray(data.agenda && data.agenda.length?
data.agenda.map(agenda=>this.createAgendaSheet(agenda)):
[])
}
)
}
createAgendaSheet(data):FormGroup{
data=data|| {} as agendaI;
return new FormGroup(
{
sheetNumber:new FormControl(data.sheetNumber),
title:new FormControl(data.title),
description:new FormControl(data.description),
}
)
}
See how this functions create an element of the array. I use the next two interface to help me to create the form
export interface agendaI {
sheetNumber: number,
title: string,
desription: string
}
export interface dataI {
filename: string,
agenda: agendaI[]
}
Well, be carefull when create the form:
<button (click)="addAgenda()">Add agenda</button>
<form *ngIf="form" [formGroup]="form">
<!--form is a FormArray, so form.controls will be formGroup-->
<div *ngFor="let control of form.controls;let i=index">
<!--in this form group...-->
<div [formGroup]="control">
<!--we have a fromControl "filename"-->
<input formControlName="filename"/><button (click)="add(i)">add</button>
<!--and a FormArray "agenda"--->
<div formArrayName="agenda">
<div *ngFor="let c of control.get('agenda').controls;let j=index" >
<div [formGroupName]="j">
<input formControlName="sheetNumber">
<input formControlName="title">
<input formControlName="description">
<button (click)="delete(i,j)">delete</button>
</div>
</div>
</div>
</div>
</div>
</form>
well, the last step is create the function add, delete and addAgenda
addAgenda()
{
this.form.push(this.createItemData(null))
}
add(i)
{
(this.form.at(i).get('agenda') as FormArray).push(this.createAgendaSheet(null))
}
delete(i,j)
{
(this.form.at(i).get('agenda') as FormArray).removeAt(j)
}
And, in ngOnInit create the form (I used a constant "data")
ngOnInit() {
this.form=new FormArray(data.map(d=>this.createItemData(d)));
}
You can see the "ugly" result in stackblitz