简体   繁体   中英

update form field value based on another field value on keydown in angular

in my angular app I have a form with some fields. On this form I have two fields, which stores percentage values and the sum of this two fields should be always 100%. Field one is enabled, the user tpyes a value in it, and on every keystroke field two should be updated. This is the goal, but I can't get it working.

This are the two fields:

 <dxi-item dataField="fix" [label]="{text: 'Fix %'}" editorType="dxNumberBox" [editorOptions]="{format: '#,##0.00\\'%\\'', onKeyDown: fixChanged, valueChangeEvent: 'keyup'}"> <dxi-validation-rule type="required" message="A mező kitöltése kötelező"></dxi-validation-rule> </dxi-item> <dxi-item dataField="variable" [label]="{text: 'Változó %'}"> <dx-number-box disabled="true" [(value)]="varPercent" format="#,##0.00'%'"></dx-number-box> </dxi-item>

And this is the fixChanged event:

 fixChanged = (e) => { setTimeout(() => { let fix = e.component.option('value'); this.fixPercentChanged.emit(100 - fix); }, 100); }

As you see, on every keystroke (keyup) I calculate the varPercent value. I logged it to the console, it works, so this isn't the issue. In the markup I use two-way binding, but the numberbox value doesn't change. Whad do I wrong?

ps: I use devextreme components, but I think, this issue is independent of this. This is a general angular issue, I think.

EDIT: I tried with an eventemitter with this markup:

 <dxi-item dataField="variable" [label]="{text: 'Változó %'}"> <dx-number-box disabled="true" [value]="varPercent" (fixPercentChange)="varPercent=$event" format="#,##0.00'%'"></dx-number-box> </dxi-item>

But no success.

At the end, I created a reference variable in the markup:

 <dxi-item dataField="variable" [label]="{text: 'Változó %'}"> <dx-number-box #varNumberBox disabled="true" format="#,##0.00'%'"></dx-number-box> </dxi-item>

And then in the codebehind I set the value of the varNumberBox :

fixChanged = (e) => {
    setTimeout(() => {
      let fix = e.component.option('value');
      this.varNumberBox.value = 100 - fix;
    }, 100); 
  }

SO is doing a very good job in motivating to answer your own questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM