Home > Back-end >  How to call keyup function on textbox for every dynamic generated form in Angular8
How to call keyup function on textbox for every dynamic generated form in Angular8

Time:01-20

I am generating form dynamically, on textbox, I am binding calculateBCT function like below <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT"> and returning result on below textbox with ngModel.

<input matInput type="text" [(ngModel)]="calculatedResult" formControlName="avgCapacity">.

Expected output - If i will enter value in Textbox0, it will call calculateBCT function and reflect result in Result0 textbox only, When i will enter value in Textbox1 it will call calculateBCT function and reflect result in Result1 textbox likewise..

Can anyone help me to get expected output

Here i have created stackblitz demo with code

CodePudding user response:

Try this, and see if it helps.

In app.component.html, make below changes:

  • Remove [(ngModel)]="calculatedResult" as you are already using formControlName
  • Pass index i to calculateBCT as (keyup)="calculateBCT($event, i)"

In app.component.ts, modify the calculateBCT method as:

    calculateBCT($event, index: number) {
      // Your existing logic goes here...
      const calculatedResult = result ? result : 0;
      // In below code, please put some checks to ensure that formControl does exist
      const formControl = this.itemTypes().at(index).get('avgCapacity');
      formControl.setValue(calculatedResult);
    }

Edit:

Since you already have formGroup available in html file, you can simply pass lineItem as 2nd parameter to calculateBCT and access formControl as const formControl = lineItem.get('avgCapacity');

  •  Tags:  
  • Related