Reputation: 3092
I have the following code to push a new item to the very end of the form array:
(<FormArray>this.invoicesForm.get('invoices')).push(this.fBuilder.group({
id: null,
issueDate: [null, Validators.required], // Only fill in and set the required validator for issue date if a custom date has already been chosen
invoiceIssuedStateCode: [0],
canEditIssueDate: [true],
chooseDate: [false],
issued: [false],
paidStatus: [0],
reference: [null],
creditNotes: this.buildCreditNotes([]),
lineItems: this.buildNewLineItems(this.lineItemsRecord.lineItems)
}));
However I need to push this item as the second last item in the array. How would I go about this?
Upvotes: 1
Views: 5013
Reputation: 1338
Instead of pushing, you could splice it:
it would work this way:
(<FormArray>this.invoicesForm.get('invoices')).controls
// splicing instead of pushing
.splice(-2, 0, this.fBuilder.group({
// your fb config
}));
notice the -2 (index -2 equals length - 2), and the 0. The -2 says where to insert or delete, the 0 that you are deleting 0 iterables, and the object you pass is then inserted (the fb.group()).
In short: you are targeting index -2 (previous to last item), you are telling it to delete 0 items, and then you are pushing at that index a new item (your formGroup object). That's how splice works!
Upvotes: 5
Reputation: 178
You can use the javascript function 'splice' over the array.
var index = (<FormArray>this.invoicesForm.get('invoices')).length-1;
fruits.splice(index, 0, this.fBuilder.group({
id: null,
issueDate: [null, Validators.required], // Only fill in and set the required validator for issue date if a custom date has already been chosen
invoiceIssuedStateCode: [0],
canEditIssueDate: [true],
chooseDate: [false],
issued: [false],
paidStatus: [0],
reference: [null],
creditNotes: this.buildCreditNotes([]),
lineItems: this.buildNewLineItems(this.lineItemsRecord.lineItems)
}));
It will add the item as second last item in the array.
Upvotes: 0