Home > OS >  OnChange doesnt work when [checked] apply in mat radio button
OnChange doesnt work when [checked] apply in mat radio button

Time:10-31

I have a problem. I tried to choose a checkbox based on an amount for first time. I applied [checked] with function for that. But after that the (change) doesnt work do you know why ?

Here's the code for the html :

 <mat-radio-group (change)="radioButtonOnChange($event)" formControlName="anticipatedPaymentOrInstallmentAdvance">
                <td td-data-table-cell>
                  <mat-radio-button id='anticipatedPayment' value="ANTICIPATED_PAYMENT" [checked]="isTwiceInstallment()">
                    {{ 'Anticipated Payment' | translate }}
                  </mat-radio-button>
                </td>
                <td td-data-table-cell>
                  <mat-radio-button id='installmentAdvance' value="INSTALLMENT_ADVANCE" [checked]="!isTwiceInstallment()" [disabled]="disableInstallmentAdvance">
                    {{ 'Installment Advance' | translate }}
                  </mat-radio-button>
                </td>
              </mat-radio-group> 

here's the code for the TS

isTwiceInstallment() {
    const overPaidAmount = this.transactionTotal -  this.nextPayment;
    const isOverPaid = overPaidAmount > 0.00;
    const isTwoTimesInstallment = this.transactionTotal >= (2 *  this.nextPayment);
    if (isTwoTimesInstallment && isOverPaid) {
      this.form.get('anticipatedPaymentOrInstallmentAdvance').setValue('ANTICIPATED_PAYMENT');
      this.disableAnticipatedPaymentDropDown = false;
      return true;
    } else {
      this.form.get('anticipatedPaymentOrInstallmentAdvance').setValue('INSTALLMENT_ADVANCE');
      this.disableAnticipatedPaymentDropDown = true;
      return false;
    }
  }
 radioButtonOnChange(event: any) {
    if (event.value === 'ANTICIPATED_PAYMENT' ) {
      this.disableAnticipatedPaymentDropDown = false;
      this.form.get('anticipatedPaymentOrInstallmentAdvance').setValue(event.value);
    }
    if (event.value === 'INSTALLMENT_ADVANCE') {
      this.disableAnticipatedPaymentDropDown = true;
      this.form.get('anticipatedPaymentOrInstallmentAdvance').setValue(event.value);
    }
  }

CodePudding user response:

Your isTwiceInstallment() function is constantly called when you have it in your template, thus it seems that you cannot change value as it basically overwrites what you are trying to do. Instead of calling that function in your template (calling functions in template is really not recommended anyway as they affect performance...), just do your checks you do in isTwiceInstallment() at an appropriate time (after building form?) call isTwiceInstallment once and leave it at that. Then your change event will work just fine.

So something like this...

buildForm() {
  // build your form first here...
  isTwiceInstallment() // call function after that...
}

and remove the function call from your template.

  • Related