首页 > 解决方案 > 表单数组推送为数组中的倒数第二项

问题描述

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

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

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

标签: angular

解决方案


而不是推,你可以拼接它:

拼接

它会这样工作:

(<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 对象)。这就是拼接的工作原理!


推荐阅读