I am trying to dynamically create a nested FormArray in my Angular 6 application.
I have a quote, which has a collection of quote-items
export class Quote {
quoteId: number;
quoteItems: QuoteItem[]
status: string;
}
export class QuoteItem {
quoteItemId: number;
description: string;
quoteItemDetails: QuoteItemDetail[]
}
export class QuoteItemDetail {
quoteItemDetailId: number;
rate: number;
quantity: number;
total: number;
}
I have a form that has the Quote object, where a user can click on a button to add and remove one or more QuoteItems.
This is my code where I initialise my form:
ngOnInit() {
this.quoteForm = this.fb.group({
status: [''],
quoteItems: this.fb.array([])
});
this.addQuoteItem();
}
And this is how I get the dynamic adding and removing working:
get quoteItems() {
return this.quoteForm.get('quoteItems') as FormArray;
}
addQuoteItem() {
this.quoteItems.push(this.fb.group({
description: '',
quoteItemDetails: this.fb.array([])
}));
}
removeQuoteV2Item(index) {
this.quoteV2Items.removeAt(index);
}
And my html:
<div formArrayName="quoteItems">
<div @items *ngFor="let item of quoteItems.controls; let contentIndex=index" [formGroupName]="contentIndex">
<input type="text" formControlName="description">
</div>
</div>
<p>
<a (click)="addQuoteItem()">Add Quote Item</a>
</p>
What I'm trying to do is then have the same functionality but for my QuoteItemDetail array. So a user can add one or more quoteItems, and within them add one or more QuoteItemDetails.
I'm really stuck at the first point, I can't work out how to get a form array assessor, this doesn't work as an example, as I'm not sure how to pass the index across:
get quoteItemDetails() {
return this.quoteItems.get('quoteItemDetails') as FormArray;
}