Search code examples
angularangular-reactive-formsngmodel

How to assign a value to ngModel dynamically in Angular onblur event


I have multiple input textbox in HTML with [(ngModel)] in it. In typescript, I am trying to assign a value to [(ngModel)] on blur event of input for all the input boxes dynamically. Tried the below approach, but did not work, Any help is much appreciated.

<input name="perStdAmount" #input [(ngModel)]="perStdAmount"  formControlName="perStdAmountCtrl" (blur)="transformAmount($event, input)">

<input name="perStepUpAmount" #input [(ngModel)]="perStepUpAmount" formControlName="perStepUpAmountCtrl" (blur)="transformAmount($event, input)">

<input name="dailyStdAmount" #input [(ngModel)]="dailyStdAmount" formControlName="dailyStdAmountCtrl" (blur)="transformAmount($event, input)">

.ts:
transformAmount(event,inputName) {
//I need to assign event.target.value to inputName.name
// inputName.name holds name of the ngModel, for example, it holds perStdAmount, onblur of first input box

//tried below but doesnt work
console.log('this.'.concat(inputName.name)); // this.perStdAmount - trying to use single function for all input box
'this.'.concat(inputName.name) = event.target.value; //throws error -The left-hand side of an assignment expression must be a variable or a property access

}

Solution

  • You can't use both ReactiveFormsModule and FormsModule at same input. Remove any one and it will work.

    <input name="perStepUpAmount" #input formControlName="perStepUpAmountCtrl" (blur)="transformAmount($event, input)"> 
    

    or

    <input name="perStepUpAmount" #input [(ngModel)]="perStepUpAmount" (blur)="transformAmount($event, input)">