Angular 5 FormArray的removeAt(i)问题

时间:2018-09-04 08:39:35

标签: typescript angular5

运行此方法后

addMoreProposals(): void {
    this.proposals.push(this.buildProposals());
    this.computeBalances();
}

computeBalances() {
 let control = this.proposalForm.controls.proposals['controls'}[this.count];
 //console.log(control)
 this.proposalForm.get('proposals.' + this.count + '.ProposedAmount').valueChanges.subscribe(value => {
     if (this.count == 0) {
         this.details.CurrentBalance = this.originalBalance - value;
     } else {
         this.details.CurrentBalance = this.latestOutstandingBalance - value
     }
 })
 this.latestOutstandingBalance = this.details.CurrentBalance;
}

然后我运行此方法,

{{1}}

当我尝试运行computeBalances时,由于控件现在为空,因此ValueChanges返回null。

请,我如何取消订阅已删除的控件,以便在运行addMoreProposals()动态添加更多表单时再次可用。

谢谢

4 个答案:

答案 0 :(得分:0)

以下是订阅的声明和销毁方式:

x: any;
mySub: Subscription;

ngOnInit() {
  this.mySub.subscribe(val => this.x = val); 
}

ngOnDestroy() {
  this.mySub.unsubscribe();
}

根据您的描述,removeAt(i)发生在computeBalances()之前。这将导致未定义的错误。

为防止这种情况,请尝试在订阅调用中调用removeAt:

this.proposalForm.get('proposals.' + this.count + '.ProposedAmount').valueChanges.subscribe(value => {
 if (this.count == 0) {
     this.details.CurrentBalance = this.originalBalance - value;
 } else {
     this.details.CurrentBalance = this.latestOutstandingBalance - value
 }
 //do the removeAt(i) here.
})

答案 1 :(得分:0)

这是我在调用removeAt(i)之前进行console.log(control)时得到的结果

FormGroup {validator:null,asyncValidator:null,_onCollectionChange:ƒ,pristine:true,touched:false,...} asyncValidator:nullcontrols:{PaymentPlan:FormControl,ProposedAmount:FormControl,StartDate:FormControl,EndDate:FormControl,Frequency: FormControl,...}脏:(...)禁用:(...)启用:(...)错误:null无效:(...)父母:(...)未决:(...)原始: trueroot:(...)状态:“ INVALID”状态更改:EventEmitter {_isScalar:false,观察者:Array(0),close:false,isStopped:false,hasError:false,......]触摸:falseuntouched:(...) updateOn:(...)valid:(...)validator:nullvalue:{PaymentPlan:null,ProposedAmount:“”,StartDate:“”,EndDate:“”,Frequency:“”,...} valueChanges:EventEmitter {_isScalar :false,观察者:Array(0),关闭:false,isStopped:false,hasError:false,...} _ onCollectionChange:ƒ()_onDisabledChange:[] _parent:FormArray {validator:null,asyncValidator:null,_onCollectionChange:ƒ,pristine :true,感动:false,...} proto :AbstractControl

console.log(i)给了我1

现在,当我单击removeAt(i)按钮以删除表单数组后,当我单击addMoreProposals()时,console.log(control)读取为未定义。谢谢

答案 2 :(得分:0)

这是整个代码

get proposals(): FormArray {
        return <FormArray>this.proposalForm.get('proposals');
    }
    addMoreProposals(): void {
        this.count++;
        this.proposals.push(this.buildProposals());
        this.computeBalances();
    }

removeProposalFields(i: number): void {
    const control = <FormArray>this.proposalForm.get('proposals');
    let removedAmount = this.proposalForm.get('proposals').value[i].ProposedAmount;
    this.latestOutstandingBalance = this.details.CurrentBalance + removedAmount;
    this.details.CurrentBalance = null;
    this.details.CurrentBalance = this.latestOutstandingBalance;

    control.removeAt(control.controls.findIndex(x => x === control));
}

computeBalances() {
    const control = <FormArray>this.proposalForm.get('proposals');

    let cont = this.proposalForm.controls.proposals['controls'][this.count];
    console.log(cont)
    if (typeof cont != typeof undefined) {
        console.log(cont)
        this.proposalForm.get('proposals.' + this.count + '.ProposedAmount').valueChanges.subscribe(value => {
            if (this.count == 0) {
                this.details.CurrentBalance = this.originalBalance - value;
            } else {
                this.details.CurrentBalance = this.latestOutstandingBalance - value
            }
        })
        this.latestOutstandingBalance = this.details.CurrentBalance;

        Observable.combineLatest(this.proposalForm.get('proposals.' + this.count + '.PaymentPlan').valueChanges,
            this.proposalForm.get('proposals.' + this.count + '.Frequency').valueChanges,
            this.proposalForm.get('proposals.' + this.count + '.StartDate').valueChanges,
            this.proposalForm.get('proposals.' + this.count + '.EndDate').valueChanges,
            this.proposalForm.get('proposals.' + this.count + '.ProposedAmount').valueChanges).subscribe(values => {
                const installmentControl = control.controls['InstallmentAmount'];
                const endDate = new Date(values[3].year, values[3].month - 1, values[3].day);
                const startDate = new Date(values[2].year, values[2].month - 1, values[2].day);
                let dateDiff = +endDate.getMonth() - +startDate.getMonth();
                let monthDifference = dateDiff + (12 * (endDate.getFullYear() - startDate.getFullYear()));
                let yearDifference = monthDifference / 12;

                if (values[0] == 1) {
                    cont.patchValue({
                        InstallmentAmount: (values[4] / (monthDifference / values[1])).toFixed(2)
                    })
                }

                else if (values[0] == 2) {
                    cont.patchValue({
                        InstallmentAmount: ((values[4]) / (monthDifference / (3 * values[1]))).toFixed(2)
                    })
                }
                else if (values[0] == 3) {
                    cont.patchValue({
                        InstallmentAmount: ((values[4]) / (yearDifference / (2 * values[1]))).toFixed(2)
                    })
                }

                else if (values[0] == 4) {
                    cont.patchValue({
                        InstallmentAmount: ((values[4]) / (yearDifference / (values[1]))).toFixed(2)
                    })
                }

                else {
                    cont.patchValue({
                        InstallmentAmount: (values[4] / values[1]).toFixed(2)
                    })
                }
            })


        control.controls['PaymentPlan'].valueChanges.subscribe(value => {
            const freqControl = control.controls['Frequency'];
            if (value == 3 || value == 4 || value == 5) {
                cont.patchValue({
                    Frequency: 1
                })
                freqControl.disable()
                freqControl.clearValidators()
            }
            else {
                freqControl.setValidators(Validators.required);
                cont.patchValue({
                    Frequency: ''
                })
                freqControl.enable();

            }
        })
    }
    else {
        //this.proposals.push(control)
    }
}


ngOnDestroy(): void {
    this.subscription.unsubscribe()
    this.busy.unsubscribe()
}

答案 3 :(得分:0)

谢谢,我认为现在已经解决了。我放了

his.myFormValueChanges$ = this.proposalForm.controls['proposals'].valueChanges;
        this.myFormValueChanges$.subscribe(units => this.updateCalculations(units));

在我的ngOnInt();

然后我像这样实现了updateCalculations

private updateCalculations(units: any) {
        const control = <FormArray>this.proposalForm.controls['proposals'];
        // console.log(units)
        for (let i in units) {
            if (units[i].ProposedAmount != '') {
                if (i == "0") {
                    this.details.CurrentBalance = this.originalBalance - units[i].ProposedAmount;
                }
                else {
                    this.details.CurrentBalance = this.latestOutstandingBalance - units[i].ProposedAmount;
                }
                this.latestOutstandingBalance = this.details.CurrentBalance;
            }



            const endDate = new Date(units[i].EndDate.year, units[i].EndDate.month - 1, units[i].EndDate.day);
            const startDate = new Date(units[i].StartDate.year, units[i].StartDate.month - 1, units[i].StartDate.day);
            let dateDiff = +endDate.getMonth() - +startDate.getMonth();
            let monthDifference = dateDiff + (12 * (endDate.getFullYear() - startDate.getFullYear()));
            let yearDifference = monthDifference / 12;

            if (units[i].PaymentPlan == 1) {
                control.at(+i).get('InstallmentAmount').setValue((units[i].ProposedAmount / (monthDifference / units[i].Frequency)).toFixed(2), { onlySelf: true, emitEvent: false })
            }

            else if (units[i].PaymentPlan == 2) {
                control.at(+i).get('InstallmentAmount').setValue(((units[i].ProposedAmount) / (monthDifference / (3 * units[i].Frequency))).toFixed(2), { onlySelf: true, emitEvent: false })

            }
            else if (units[i].PaymentPlan == 3) {
                control.at(+i).get('InstallmentAmount').setValue(((units[i].ProposedAmount) / (yearDifference / (2 * units[i].Frequency))).toFixed(2), { onlySelf: true, emitEvent: false })
            }

            else if (units[i].PaymentPlan == 4) {
                control.at(+i).get('InstallmentAmount').setValue(((units[i].ProposedAmount) / (yearDifference / units[i].Frequency)).toFixed(2), { onlySelf: true, emitEvent: false })

            }

            else {
                control.at(+i).get('InstallmentAmount').setValue((units[i].ProposedAmount / units[i].Frequency).toFixed(2), { onlySelf: true, emitEvent: false })

            }

        }

现在一切正常。谢谢您的帮助