表单数组推送作为数组的倒数第二个

时间:2019-06-07 12:05:07

标签: angular

我有以下代码将新项目推送到表单数组的最后:

(<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)
        }));

但是,我需要将此项目作为数组中的倒数第二个项目推送。 我该怎么办?

2 个答案:

答案 0 :(得分:0)

代替推送,您可以拼接它:

Splice

它将以这种方式工作:

(<FormArray>this.invoicesForm.get('invoices')).controls
    // splicing instead of pushing
    .splice(-2, 0, this.fBuilder.group({
            // your fb config
        }));

请注意-2(索引-2等于长度-2)和0。-2表示要插入或删除的位置,0表示要删除的0迭代对象,然后插入要传递的对象( fb.group())。

简而言之:您要定位索引-2(位于最后一个项目之前),告诉它删除0个项目,然后在该索引处推送一个新项目(您的formGroup对象)。这就是拼接的工作方式!

答案 1 :(得分:0)

您可以在数组上使用javascript函数'splice'。

["111","222", "333"]

它将添加该项目作为数组中的倒数第二个项目。