removeAt (i) проблемы с Angular 5 FormArray - PullRequest
0 голосов
/ 04 сентября 2018

После запуска этого метода

const control = <FormArray>this.proposalForm.get('proposals');
control.removeAt(i);

А потом я запускаю этот метод,

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

Когда я пытаюсь запустить computeBalances, ValueChanges возвращает ноль, так как элемент управления теперь нулевой.

Пожалуйста, как я могу отписать удаленные элементы управления, чтобы они снова были доступны, когда я запускаю addMoreProposals () для динамического добавления других форм.

Спасибо

Ответы [ 4 ]

0 голосов
/ 05 сентября 2018

Спасибо, я думаю, что это решено сейчас. Я положил т

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

в моем ngOnInt ();

Тогда я реализовал обновление Расчётов вот так

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

            }

        }

Теперь все работает отлично. Спасибо за вашу помощь

0 голосов
/ 05 сентября 2018

Это то, что я получил, когда сделал console.log (control) до того, как вызвал removeAt (i)

FormGroup {validator: null, asyncValidator: null, _onCollectionChange: ƒ, нетронутый: true, трогательный: false,…} asyncValidator: nullcontrols: {PaymentPlan: FormControl, ProposedAmount: FormControl, StartDate: FormContcy: EndCateControl, End, End FormControl,…} dirty: (...) отключено: (...) включено: (...) ошибки: nullinvalid: (...) родитель: (...) в ожидании: (...) нетронутый: trueroot: (...) status: «INVALID» statusChanges: EventEmitter {_isScalar: false, наблюдатели: Array (0), закрыто: false, isStopped: false, hasError: false,…} трогано: falseuntouched: (...) updateOn: (...) действительный: (...) валидатор: 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: ƒ, prist : правда, тронут: ложь,…} proto : AbstractControl

console.log (i) дал мне 1

Теперь, после того как я нажал на кнопку removeAt (i), чтобы удалить formarray, мой console.log (control) прочитал undefined, когда я нажал на addMoreProposals (). Спасибо

0 голосов
/ 05 сентября 2018

Это весь код

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()
}
0 голосов
/ 04 сентября 2018

Вот как подписывается и уничтожается подписка:

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.
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...